php

Upload File in PHP

File uploading is a common task for web applications. Different types of files are required to upload based on the application. Image files, text files, pdf files, XML files, etc. can be uploaded by using PHP script. One or more files can be uploaded by PHP. There are some PHP directives in the php.ini configuration file and PHP built-in functions related to file upload which is discussed in this tutorial. HTML has a particular attribute in the form tag for file uploading tasks, that is enctype.

PHP Directives for File Upload

PHP Directive Purpose
file_uploads The value of this directive must be On to upload the file using PHP script. The default value of this directive is On.
upload_tmp_dir It is used to set the temporary directory where the file will be uploaded.
upload_max_filesize It is used to set the maximum size of the file that can be uploaded.
max_file_uploads It is used to set the number of files that can be uploaded.
post_max_size It is used to set the maximum size of the POST data and the value of this directive must be more than the value of the upload_max_filesize directive because the file is uploaded by the POST request.
max_input_time It is used to set the maximum amount of time to read the data of the uploading file.
max_execution_time It is used to set the maximum amount of time in seconds to execute the script for uploading the file.
memory_limit It is used to set the maximum memory size required for executing a PHP script for uploading the file.

PHP Functions for File Upload

Two built-in functions are mainly used in PHP for uploading the file which is mentioned below.

A. is_uploaded_file()
It is used to check whether the file is uploaded through the HTTP POST which helps to prevent an attack from the malicious user.

B. move_uploaded_file()
It is used to move the uploaded file into the web server location. This function will return true if the file is uploaded and moved successfully.

PHP File Uploading Variable

The $_FILES array variable stores all information related to uploading a file into the server. It is a superglobal variable of the PHP that is accessible anywhere from the script. It contains five types of information: filename, type, size, temporary filename, and errors related to uploading the file. The purpose of each value of the $_FILE array has been mentioned below. Suppose the name of the upload field name is ‘upload’ here.

A. $_FILES[‘upload’][‘name’]
It is used to get the original filename that has been uploaded by the client’s computer.

B. $_FILES[‘upload’][‘tmp_name’]
It is used to get the temporary filename that has been stored in the server temporarily.

C. $_FILES[‘upload’][‘type’]
It is used to get the mime type of the uploaded file.

D. $_FILES[‘upload’][‘size’]
It is used to get the size of the uploaded file in bytes.

E. $_FILES[‘upload’][‘error’]
It is used to get the error code that is related to the uploading task. The variable may contain any of the 7 types of values that are mentioned below.

Error Code Description
1- UPLOAD_ERR_OK It generates when the file uploads successfully.
2- UPLOAD_ERR_INI_SIZE It generates if the file size exceeds the value of the upload_max_filesize directive that is defined in the php.ini file.
3- UPLOAD_ERR_PARTIAL It generates if the file size exceeds the value of the MAX_FILE_SIZE directive that is defined in the HTML Form.
4- UPLOAD_ERR_NO_FILE It generates if no file is uploaded.
5- UPLOAD_ERR_NO_TMP_DIR It generates if no temporary directory is missing.
6- UPLOAD_ERR_CANT_WRITE It generates if there is no write permission in the server location.
7- UPLOAD_ERR_EXTENSION It generates if the PHP extension stops the uploading task.

Uploading File Using PHP

Different examples of uploading the file using PHP script have been shown in this part of the tutorial.

Example 1: Upload any Type of File

You can upload the file in the current location from where the PHP script is executing or in a particular folder. You have to create the folder in the server location to upload a file inside a particular folder before executing the PHP script. I have created a folder named ‘uploads’ inside the working folder. Create a PHP file with the following script that will upload a file of any type inside the ‘uploads’ folder. An HTML form with a file type field and a submit button has been used in the script to select the file from the client’s computer for uploading. If 1 is generated as an error code after uploading the file, the file is uploaded successfully. Next, the move_upload_file() function has been used to move the uploaded file to the server location. The success message will be printed if the file is uploaded into the server location successfully; otherwise, an error message will be displayed.

<?php

//Check any file is selected or not
if (isset($_FILES['uploadFile']))
{
   //Check any uploading error exists or not
   if ($_FILES['uploadFile']['error'] === UPLOAD_ERR_OK)
   {
     //Read the original filename
     $fileName = $_FILES['uploadFile']['name'];
     //Read temporary filename
     $fileTempPath = $_FILES['uploadFile']['tmp_name'];
 
     //Set the uploading file path
     $filePath = dirname(__FILE__).'/uploads/'.$fileName;

     //Upload the file using move_upload_file() function
     if(move_uploaded_file($fileTempPath, $filePath))
     {
       //Print the success message
       echo '<h3 style="text-align:center">File is uploaded successfully.</h3>';
     }
     else
     {
       //Print the error message
       echo '<h3 style="text-align:center">Error uploading the file.<br />'. $_FILES['uploadFile']['error']. '</h3>';
     }
  }
  else
  {
     //Print the error message
     echo '<h3 style="text-align:center">Error uploading the file.<br />'. $_FILES['uploadFile']['error']. '</h3>';
   }
}
else
{
?>

<!-- Show the uploading form -->
<html>
    <body>
        <div style = "text-align: center;">
            <h3>Uploading file using PHP</h3>
            <form action="#" method="POST" enctype="multipart/form-data">
                Select File: <input type="file" name="uploadFile" />
                    <input type="submit" value="Upload" />
            </form>
        </div>
    </body
</html>

<?php

}

?>

Output
The following output will appear if the script is executed from the web server.

Click on the Browse button to select the file for uploading and press the upload button to upload the file into the server.

The following message will appear if the file is uploaded successfully.

Example 2: Upload a File of the Specific Type and Size

The way of uploading the file using a separate HTML file and PHP file has been shown in this example. Create an HTML file with the following script to display the form for uploading the file.

uploadForm.html

<!-- Show the uploading form -->
<html>
    <body>
        <div style = "text-align: center;">
            <h3>Uploading JPEG file using PHP</h3>
                <form action="#" method="POST" enctype="multipart/form-data">
                    Select File: <input type="file" name="uploadFile" />
                    <input type="submit" value="Upload" />
                </form>
            </div>
    </body
</html>

Create a PHP script with the following script that will upload the JPEG file only and the size will be less than 300000 bytes. The file type and size have been read by using $_FILES[‘uploadFile’][‘type’] and $_FILES[‘uploadFile’][‘size’] variables. The success message will appear if the uploaded file type and size match the criteria defined in the ‘if’ condition; otherwise an error message will be displayed.

upload2.php

<?php

//Check any file is selected or not
if (isset($_FILES['uploadFile']))
{
   //Check any uploading error exists or not
   if ($_FILES['uploadFile']['error'] === UPLOAD_ERR_OK)
   {
      //Read the original filename
      $fileName = $_FILES['uploadFile']['name'];
      //Read temporary filename
      $fileTempPath = $_FILES['uploadFile']['tmp_name'];
      //Read the file size
      $fileSize = $_FILES['uploadFile']['size'];
      //Read the file type
      $fileType = $_FILES['uploadFile']['type'];
 
      //Check the file type and the file size
      if ($fileType == 'image/jpeg' && $fileSize < 300000)
      {
         //Set the uploading file path
         $filePath = dirname(__FILE__).'/uploads/'.$fileName;
 
         //Upload the file using move_upload_file() function
         if(move_uploaded_file($fileTempPath, $filePath))
         {
            //Print the success message
            echo '<h3 style="text-align:center">File is uploaded successfully.</h3>';
         }
         else
         {
            //Print the error message
           echo '<h3 style="text-align:center">Error uploading the file.<br />'. $_FILES['uploadFile']['error']. '</h3>';
        }
     }
     else
        //Print the error message
        echo '<h3 style="text-align:center">File type or size is not supported.</h3>';
   }
   else
   {
      //Print the error message
      echo '<h3 style="text-align:center">Error uploading the file.<br />'. $_FILES['uploadFile']['error']. '</h3>';
   }
   include('uploadForm.html');
}
else
   include('uploadForm.html');
?>

Output
In the following output, the flower.png file has been selected that is not a JPEG file:

The following output will appear after pressing the Upload button:

Here, the flower1.jpeg file has been selected which is a JPEG file.

Now, the following output will appear after pressing the Upload button:

Example 3: Check the File Before Uploading

Create a PHP file with the following script that uses the is_uploaded_file() function to check whether the file is uploaded through the HTTP POST before moving the file to the server. The script will upload the text file only and print the content of the text file after uploading the file successfully.

<?php

//Check whether any file is selected or not
if (isset($_FILES['uploadFile']))
{
   //Read the original filename
   $fileName = $_FILES['uploadFile']['name'];
   //Read temporary filename
   $fileTempPath = $_FILES['uploadFile']['tmp_name'];
   //Read the file type
   $fileType = $_FILES['uploadFile']['type'];
   //Set the uploading file path
   $filePath = dirname(__FILE__).'/uploads/'.$fileName;
   //Check the file type
   if ($fileType == 'text/plain')
   {
      //Check any uploading error exists or not
      if ($_FILES['uploadFile']['error'] === UPLOAD_ERR_OK)
      {
         if (is_uploaded_file($fileTempPath)) {
           //Upload the file using move_upload_file() function
           if(move_uploaded_file($fileTempPath, $filePath))
           {
              //Print the success message
              echo $fileName ." is uploaded successfully.<br />";
              echo "The content of the file:<br />";
              readfile($filePath);

           }
           else
           {
              echo 'Error uploading the file.<br />'. $_FILES['uploadFile']['error'];
           }
        }
        else {
           echo "File is not uploaded.";
        }
     }
   }
   else
     echo "File is not a text file.";
}
else
{

?>


<!-- Show the uploading form -->
    <html>
        <body>
            <div style = "text-align: center;">
                <h3>Uploading file using PHP</h3>
                <form action="#" method="POST" enctype="multipart/form-data">
                    Select File: <input type="file" name="uploadFile" />
                    <input type="submit" value="Upload" />
                </form>
            </div>
        </body
</html>

<?php

}

Output
In the following output, a text file has been selected for uploading:

The content of the file has been shown in the output after uploading the file successfully.

Conclusion

The file uploading task is a common requirement for any web application. The uses of the file uploading variable and the built-in functions of PHP have been shown in this tutorial by using multiple file uploading examples. If you want, you can upload more than one file at a time by using the PHP script that is covered in this tutorial. You can also upload a folder that contains multiple files by using the PHP script.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.