How to Upload on Video and Send to Another Page in Php

php file upload

Uploading files from clients to servers is one of the important features of any PHP application. However, the implementation of features with proper security and hassle-complimentary configuration could be tricky. Developers could use several PHP file upload scripts to ensure that the application offers this feature seamlessly.

  1. Prerequisites
  2. The Process of File Uploading in PHP
  3. Create the HTML Form
  4. Using jQuery & AJAX for File Upload Form
  5. Configure and Connect MySQL Database With PHP
  6. Create a PHP Script for File Uploading
  7. Check if in that location are whatsoever errors in the upload
  8. Bank check that the file is nether the ready file size limit
  9. How to Use reCAPTCHA in PHP Contact Form?
  10. Wrapping Upwardly

I will discuss a popular strategy that developers could integrate within their projects. In this article, I will show you how you can add together PHP file upload functionality on your website using jQuery, AJAX, and MySQL.

Prerequisites

For this PHP file uploading case, I presume that y'all accept a PHP awarding installed on a web server. My setup is:

  • PHP 7.1
  • MySQL
  • JQuery/Ajax file

To brand sure that that I don't go distracted past server-level issues, I decided to host my PHP application on Cloudways managed servers considering it takes intendance of server-level issues and has a great devstack right out of the box. You can try out Cloudways for free by signing for an account.

Get the ultimate tool list for Developers

We'll send a download link to your inbox.

Thank You

Your Ebook is on it's Way to Your Inbox.

Now, that the configurations are ready, I will next work on the File Uploading Script.

Related Manufactures:

Multiple Images and Files Upload in Laravel with Validation

Upload Image and File in CodeIgniter

The Procedure of File Uploading in PHP

The process of a complete PHP file uploading script is as follows:

  • Create a Bootstrap powered HTML Upload form as the "frontend" of the script
  • Ajax scripts for file upload
  • Apply security checks
  • Create PHP scripts to handle/procedure data

Create the HTML Grade

The HTML grade is the interface through which the user interacts and submits the information. But to make the form work with the file, <form> element must take its method set to Mail service because files can not be sent to servers using the Go method.

Another important attribute is enctype which should be prepare to multipart/grade-information. Last merely not least, the file <input> type attribute should be set to file.

Create a file alphabetize .php in your PHP project and blazon in the following code.

<!doctype html> <html> <head lang="en"> <meta charset="utf-8"> <title>Ajax File Upload with jQuery and PHP</title> <link rel="stylesheet" href="way.css" blazon="text/css" /> <script type="text/javascript" src="js/jquery-1.eleven.3-jquery.min.js"></script> <script type="text/javascript" src="js/script.js"></script>  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.iii.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <torso> <div grade="container"> <div course="row">  <div class="col-md-eight">  <h1><a href="#" target="_blank"><img src="logo.png" width="80px"/>Ajax File Uploading with Database MySql</a></h1> <hr>   <form id="form" activeness="ajaxupload.php" method="mail service" enctype="multipart/grade-data"> <div class="form-group"> <label for="name">NAME</label> <input blazon="text" class="form-control" id="proper name" name="name" placeholder="Enter proper name" required /> </div> <div grade="grade-group"> <label for="electronic mail">Email</characterization> <input blazon="email" form="form-control" id="email" proper noun="electronic mail" placeholder="Enter e-mail" required /> </div>  <input id="uploadImage" type="file" take="paradigm/*" name="image" /> <div id="preview"><img src="filed.png" /></div><br> <input class="btn btn-success" type="submit" value="Upload"> </form>  <div id="err"></div> <hr> <p><a href="https://world wide web.cloudways.com" target="_blank">world wide web.Cloudways.com</a></p> </div> </div> </div></body></html>

html ajax file uploading form

In this grade, I accept used Bootstrap Classes to use a little flake of styling on the course. In this form, I take mentioned ajaxupload.php in the action attribute of the grade.

Stop Wasting Time on Servers

Cloudways handle server direction for you so y'all can focus on creating not bad apps and keeping your clients happy.

Using jQuery & AJAX for File Upload Form

Since I will utilise jQuery & AJAX for submitting data and uploading the files, I will get-go by including the jQuery library showtime.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>        
$(document).ready(function (e) {  $("#class").on('submit',(function(e) {   east.preventDefault();   $.ajax({          url: "ajaxupload.php",    blazon: "POST",    data:  new FormData(this),    contentType: false,          cache: faux,    processData:false,    beforeSend : function()    {     //$("#preview").fadeOut();     $("#err").fadeOut();    },    success: role(data)       {     if(data=='invalid')     {      // invalid file format.      $("#err").html("Invalid File !").fadeIn();     }     else     {      // view uploaded file.      $("#preview").html(data).fadeIn();      $("#grade")[0].reset();      }       },      error: function(e)        {     $("#err").html(e).fadeIn();       }               });  })); });

In the in a higher place code using the $ajax() method for sending data to php also bank check the success data or error in data sending.

Configure and Connect MySQL Database With PHP

The side by side step is setting up and configuring the MySQL database. Go to the Cloudways Database Manager and create a tabular array named 'uploading'. The fields of this tabular array are name, e-mail, file_name. Alternatively, you could apply the following SQL query:

CREATE Table `uploading` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `proper noun` varchar(100) COLLATE utf8_unicode_ci Not Zip,  `email` varchar(100) COLLATE utf8_unicode_ci Not Aught,  `file_name` varchar(100) COLLATE utf8_unicode_ci NOT Nada,  PRIMARY Fundamental (`id`)  ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Next, create db.php to connect the database with the PHP application. Paste the following code snippet in the file:

<?php  //DB details  $dbHost = 'localhost';  $dbUsername = 'fkmc';  $dbPassword = '';  $dbName = 'fkc';  //Create connection and select DB  $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);  if($db->connect_error){     die("Unable to connect database: " . $db->connect_error);  }

Create a PHP Script for File Uploading

When the user interacts with this course, the file is uploaded to the temporary folder and all the data about the file is stored in the multidimensional assortment known as $_FILES .The Key Index of this array is the name attribute on this <input type=''file' proper name="epitome" > field.

In this case, $_FILES["image"] is the index name.more than data about the file is stored in the following indexes.

<?php  $img = $_FILES["image"]["name"] stores the original filename from the client $tmp = $_FILES["image"]["tmp_name"] stores the name of the designated temporary file $errorimg = $_FILES["prototype"]["fault"] stores whatever error code resulting from the transfer ?>        

Once the file has been uploaded to the temporary folder and all its information saved in the array, the move_uploaded_file() role is used to move the file from its present temporary location to a permanent location. The process of uploading the file is as follows:

  1. Check if in that location are whatever errors in the upload.
  2. Check if the file type is immune
  3. Check that the file is under the set file size limit
  4. Check if the filename is valid (if the filename has a /, it will bear on the destination path).
  5. Check that the file doesn't already exist at the target location (based on the name).
  6. Finally, upload the file.

Permit's create the PHP script to deal with the functionality of file uploading. Create ajaxupload .php and blazon the following code in information technology.

<?php  $valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp' , 'pdf' , 'doc' , 'ppt'); // valid extensions $path = 'uploads/'; // upload directory  if(!empty($_POST['name']) || !empty($_POST['electronic mail']) || $_FILES['image']) { $img = $_FILES['prototype']['proper noun']; $tmp = $_FILES['image']['tmp_name'];  // get uploaded file'due south extension $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));  // can upload same image using rand function $final_image = rand(1000,one thousand thousand).$img;  // check's valid format if(in_array($ext, $valid_extensions))  {  $path = $path.strtolower($final_image);   if(move_uploaded_file($tmp,$path))  { echo "<img src='$path' />"; $proper noun = $_POST['proper noun']; $electronic mail = $_POST['email'];  //include database configuration file include_once 'db.php';  //insert course data in the database $insert = $db->query("INSERT uploading (name,e-mail,file_name) VALUES ('".$name."','".$email."','".$path."')");  //echo $insert?'ok':'err'; } }  else  { repeat 'invalid'; } } ?>

Now that all the checks have been coded in, I will move the uploaded file from the tmp folder to the upload folder. For this, commencement, create an upload folder in the project directory. This is where the uploaded pictures will be saved. Where pathinfo() is the built-in function which will render the filename and extension in separate indexes.

Check if there are whatever errors in the upload

To check the error in the uploaded file, type in the following code, If the error is greater than nada and so there must be an error in the procedure.

if($errorimg > 0){     die('<div class="alert alert-danger" office="alarm"> An error occurred while uploading the file </div>');  }

Bank check that the file is under the fix file size limit

The file size is measured in bytes. Then, if the file size is gear up at 500kb, then the file size should be less than 500000.

if($myFile['size'] > 500000){     die('<div form="alert alert-danger" role="alert"> File is too big </div>');  }

Where move_uploaded_file is the role which will movement the file from $myFile["tmp_name"] (temporary location) to "upload/" . $name (permanent location) also check the database tabular array record will be inserted.

insert file in database

How to Use reCAPTCHA in PHP Contact Grade?

Recaptcha is a gratis service that protects forms from spamming and abusive submission. It's an additional layer that works behind-the-scenes to prevent any spamming by differentiating if the end-user is a man or a bot, and give them the claiming to solve.

To place a reCAPTCHA on your PHP website, you must use a simple library that wraps around a reCHAPTCHA API. Y'all can download the "reCAPTCHA PHP Library" and then use the file 'recaptchalib.php'.

Add the following code in the <form> tag where you desire your reCAPTCHA to be placed:

require_once('recaptchalib.php'); $publickey = "your_public_key"; //you got this from the signup page echo recaptcha_get_html($publickey);        

To check whether the users have submitted the correct answers or not, a "verify.php" file needs to exist created and should be fix every bit an 'activeness' parameter in the <form> tag. Hither is the lawmaking below:

<?php   require_once('recaptchalib.php');   $privatekey = "your_private_key";   $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);   if (!$resp->is_valid) {     dice ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .          "(reCAPTCHA said: " . $resp->error . ")");   }    else {     // Your code hither to handle a successful verification   } ?>          

Q: How to modify the maximum upload file size in PHP?

A: To upload PHP scripts, the default maximum upload size is 128 MB. However, y'all can e'er increase its upload limit by editing the upload_max_filesize value from the php.ini file.

Q: Which the all-time PHP library for file uploading?

A: Though there are several files uploading PHP libraries available in the market, the best one to utilize is the HTML5 File Upload library. It is very easy to employ and the most pop library amongst the developers, as it simplifies file uploading and validation in a few quick steps.

Q: Where can I download the PHP file upload script?

A: You can easily download file uploading script from phpfileuploader.com, it provides an easy to use and highly avant-garde file uploading script that precisely upload files to the server without refreshing the folio. Using the script, you can easily upload multiple files and new additional files during the upload procedure.

Q: How to move uploaded files in PHP?

A: To move the uploaded file to a new path/directory, yous can utilise the move_uploaded_file() function to operate. It allows united states to easily movement the files to a new location fifty-fifty if they are newly uploaded. Upon successful transfer, it returns TRUE and if caught any exception, returns Simulated.

Wrapping Upwards

In this tutorial, I demonstrated epitome and file upload in PHP using AJAX and jQuery. Here is a functional demo of the application where y'all could encounter the app in activeness. In my adjacent tutorial, I will demonstrate how yous could upload and store a file into the database using PDO .

Share your stance in the comment section. Annotate Now

Share This Commodity

Customer Review at

"Cloudways hosting has 1 of the best client service and hosting speed"

Sanjit C [Website Programmer]

Saquib Rizwan

Saquib is a PHP Community Expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is well versed in PHP and regularly contributes to open source projects. For fun, he enjoys gaming, movies and hanging out with friends. You can email him at [electronic mail protected]

bowmantionvits.blogspot.com

Source: https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/

0 Response to "How to Upload on Video and Send to Another Page in Php"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel