Tuesday, March 10, 2020

Upload File/Image in PHP

A PHP script can be used with an HTML form to allow users to upload files to the server. Initially, files are uploaded into a temporary directory and then relocated to a target destination by a PHP script. You can upload any kind of file like images, videos, ZIP files, Microsoft Office documents, PDFs, as well as executables files and a wide range of other file types.
The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can get file name, file type, file size, temp file name and errors associated with file.

Step 1: Creating an HTML form to upload the file

The following example will create a simple HTML form that can be used to upload files.

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>File Upload Form</title> </head> <body> <form method="post" enctype="multipart/form-data"> <h2>Upload File</h2> <label for="fileSelect">Filename:</label> <input type="file" name="uploadfile" id="fileSelect"> <input type="submit" name="submit" value="Upload"> </form> </body> </html>

Note: In addition to a file-select field the upload form must use the HTTP post method and must contain an enctype="multipart/form-data" attribute. This attribute ensures that the form data is encoded as mulitpart MIME data — which is required for uploading the large quantities of binary data such as image, audio, video, etc.

Step 2: Processing the uploaded file

 include 'connection.php';  
 $file = $_FILES['uploadfile'];  
 $filename = $_FILES['uploadfile']['name'];  
 $filetmp = $_FILES['uploadfile']['tmp_name'];  
 $upload = "upload/".$filename;  
 $query = "insert into upload values ('$upload')";  
 $data = mysqli_query($conn, $query);  
   echo "Image to be Uploaded:"."<br><br>";  
   echo "<img src='$upload' width='150'>";  
   echo "Image not Uploaded";  

Explanation of Code

Once the form is submitted information about the uploaded file can be accessed via PHP super global array called $_FILES.  
  • $file = $_FILES['uploadfile'] : Global variable to store file information in an array.  
  • $filetmp = $_FILES['uploadfile']['tmp_name']: Store temporary name of the file uploaded.  
  • $upload = "upload/".$filename : This will store the uploaded file in the upload folder on server. We have to create upload folder on server. In this case htdocs->phpcode as your default server location for upload folder. 

  • move_uploaded_file($filetmp,$upload): This php function will upload file into destination folder at server location.  
  • $query = "insert into upload values ('$upload')" :  This will store upload file location in the database as string.