Uploading Files in PHP using Forms

PHP

When you have to allow users to upload files using HTML forms and PHP, it is quite simple. All you have to use is $_FILES super global and it will upload the file. You can also set additional options like giving the uploaded file a file name and selecting the upload directory. You can also verify whether the uploaded file is of certain type like images so that people just don’t upload random files that may compromise your website.

For uploading the files, we will have to build an HTML form and use the POST method to process it. We also have to add some additional parameter to the form which is enctype=”multipart/form-data”. This part tells how the form should be encrypted when it is processed. It can only be used with the POST method.

Follow the examples below to build a simple html form that allows users to browse the file in their system. Then after a file is selected, the form needs to be submitted. The submission is then processed by PHP, some verification is done and the file is moved to a directory on the server.

HTML Form:

<form action="fileupload.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Select your image file: <input name="image" type="file" />
<br />
<input type="submit" name="submit" value="Upload Image" />
</form>
Output:


Select your image file: 


Notes:

  1. The use of MAX_FILE_SIZE hidden form field is to specify the maximum upload file size.
  2. The size is measured in bytes.
  3. This hidden field should be placed before the file browsing field in HTML.

PHP Script fileupload.php

<?php
$upload_directory = "user-uploads/";
$file_name = basename($_FILES['image']['name']);
$upload_file = $upload_directory.$file_name;
if(move_uploaded_file($_FILES['image']['tmp_name'],$upload_file)){
echo "Your file ".$file_name." has been uploaded";
}else{
echo "There was an error uploading your file";
}
?>
Notes:

  1. See how the uploading directory and user file name are used along with move_uploaded_file function.
  2. $_FILES handles the uploaded file and it is further processed into the directory giving it a file name using move_uploaded_file.
  3. The above script does not check whether the same file name already exists and will overwrite it directly.
  4. $_FILES superglobal stores various other information in an array.

Here is what it stores in an example:

Array (
 [image] => Array (
  [name] => file-name.jpg
  [type] => image/jpeg
  [tmp_name] => /var/tmp/phpxUwhwX
  [error] => 0
  [size] => 6361 )
 )