File upload in PHP allows you to upload files with different extensions to the server. We can use HTML forms and enable the users to upload files to the server. These files are stored in a temporary directory unless moved to a target location for permanent storage. But for the file upload in PHP to work, we have to ensure some configuration settings are set appropriately.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

How to Configure PHP Settings to Ensure Smooth File Upload in PHP?

We need to configure specific settings to enable the file upload in PHP. Without these settings done right, the upload will be unsuccessful or not how we want it to operate. To configure these settings, we need to find the php.ini file.

If you are aware of the php.ini file location, it’s well and good. But if you don’t know the exact location, use the below code to locate it.

<? php echo php_ini_loaded_file(); ?>

php_ini_loaded_file() is a built-in function. Create a PHP file with this code and open it from your browser through a local server to get the location of the php.ini file. Once you have the location, you need to find and configure some settings. The primary settings along with recommended values are:

; Allows file uploads

file_uploads = On

;  Temporary directory where upload files are temporarily stores

upload_tmp_dir = 

; Max file size approval

upload_max_filesize = 16M

; Max files upload allowed per request

max_file_uploads = 20

; POST data max size accepted by PHP

post_max_size = 20M

max_input_time = 60

memory_limit = 128M

max_execution_time = 30

What Are the Best Key Settings for File Upload in PHP?

  • file_uploads: The file_uploads key defines whether to allow file upload or not. By default, it is set to On, and that’s exactly what we want it to be.
  • upload _max_filesize: This key describes the maximum file size allowed while uploading. You might have seen this while uploading your profile picture on some platforms. When you upload a greater resolution image, it says a file size of (n)MB is allowed. This key is what handles the maximum file size allowance part for PHP code. The default size is set to 2MB. But you can change it according to your preference and requirement. You can also access and alter this key’s settings from the .htaccess file.
  • upload_tmp_dir: This is the directory that stores the uploaded file temporarily. You can set it to anything. However, if you don’t provide a path here, the system will choose a default path as the temporary directory.
  • post_max_size: This key allows you to set the maximum limit for storing the POST data. When using the file upload in PHP, the file is sent and stored along with POST requests’ data. Thus, it should always be greater than the upload_max_filesize value.
  • max_file_uploads: With this key setting, you can configure the number of maximum files uploaded through a single request. The default value for the max_file_uploads key is 20.
  • max_input_time: This directive defines the maximum amount of time allowed for the PHP script to parse the input data of the uploaded file(s). The value is specified in seconds, and 60 seconds is usually a good amount.
  • memory_limit: The key indicates the maximum memory the PHP script can consume. The default size is 128MB, which is a considerable amount. However, if you are still facing challenges while uploading large files, increase the number. Another thing worth noting is always to keep the number greater than that of the post_max_size value.
  • max_execution_time: It indicates the maximum number of time in seconds allowed for the script to run. The value of this key should be directly proportional to the size of the files uploaded.

Learn 15+ In-Demand Tools and Skills!

Automation Testing Masters ProgramExplore Program
Learn 15+ In-Demand Tools and Skills!

Creating the HTML Form for File Upload in PHP

Now that we are done with the configuration settings let's move ahead with creating an HTML form for uploading the file. For this, we will be creating the index.php file and save it inside a folder. Below is the code for the index.php file.

<?php

session_start(); 

?>

<!DOCTYPE html>

<html>

<head>

  <title>PHP File Upload</title>

</head>

<body>

  <?php

    if (isset($_SESSION['message']) && $_SESSION['message'])

    {

      printf('<b>%s</b>', $_SESSION['message']);

      unset($_SESSION['message']);

    }

  ?>

  <form method="POST" action="fileUpload.php" enctype="multipart/form-data">

    <div>

      <span>Upload a File:</span>

      <input type="file" name="uploadedFile" />

    </div>

    <input type="submit" name="uploadBtn" value="Upload the File" />

  </form>

</body>

</html>

When you run the above code through your local server, it will give the following output.

Output:

File_Upload_in_PHP_1

Some Important Things to Note From the Form

There are some things to note in the above HTML form.

  • action="fileUpload.php": The value in the action field refers to the file that will handle the file upload in PHP. We will create the file in a moment.
  • method="POST": This value indicates the browser about the script’s action to upload the selected file.
  • enctype="multipart/form-data": This value refers to the content type of the files that will be accepted for uploading. It also indicates the type of encoding that the PHP script will use for uploading. The multipart/form-data value enables us to upload files using the POST method. It also ensures the characters of the files are not encoded while submitting the form. Besides multipart/form-data, enctype also accepts application/x-www-form-urlencoded and text/plain values.
  • The message variables used at the start of the form will display the status of the upload. They will also show successful or error messages depending on the status of the upload.

Running the file through the server will allow you to browse and choose any file from your computer.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Creating the Upload Logic for File Upload in PHP

The HTML form represents the client-side code. Now that our form is ready, let’s move towards the server-side scripting to handle the file upload in PHP. Below is the code that you need to copy in the fileUpload.php file.

<?php

session_start();

$message = ''; 

if (isset($_POST['uploadBtn']) && $_POST['uploadBtn'] == 'Upload the File')

{

  if (isset($_FILES['uploadedFile']) && $_FILES['uploadedFile']['error'] === UPLOAD_ERR_OK)

  {

    // uploaded file details

    $fileTmpPath = $_FILES['uploadedFile']['tmp_name'];

    $fileName = $_FILES['uploadedFile']['name'];

    $fileSize = $_FILES['uploadedFile']['size'];

    $fileType = $_FILES['uploadedFile']['type'];

    $fileNameCmps = explode(".", $fileName);

    $fileExtension = strtolower(end($fileNameCmps));

    // removing extra spaces

    $newFileName = md5(time() . $fileName) . '.' . $fileExtension;

    // file extensions allowed

    $allowedfileExtensions = array('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc');

    if (in_array($fileExtension, $allowedfileExtensions))

    {

      // directory where file will be moved

      $uploadFileDir = 'C:\xampp\htdocs\test';

      $dest_path = $uploadFileDir . $newFileName;

      if(move_uploaded_file($fileTmpPath, $dest_path)) 

      {

        $message = 'File uploaded successfully.';

      }

      else 

      {

        $message = 'An error occurred while uploading the file to the destination directory. Ensure that the web server has access to write in the path directory.';

      }

    }

    else

    {

      $message = 'Upload failed as the file type is not acceptable. The allowed file types are:' . implode(',', $allowedfileExtensions);

    }

  }

  else

  {

    $message = 'Error occurred while uploading the file.<br>';

    $message .= 'Error:' . $_FILES['uploadedFile']['error'];

  }

}

$_SESSION['message'] = $message;

header("Location: index.php");

Some Important Things to Note From the Upload Code

There are some things to note in the above upload code.

  • The first thing we did was to check if the file had come from a valid source or not. We used the if statement and cross-checked them with the upload button’s variables’ values.
  • When the file is uploaded, the $_Files superglobal variable is populated with the following information:
    • tmp_name: Temporary path that holds the upload file
    • name: Name of the file
    • size: The size of the uploaded file in bytes
    • type: Information about the mime type of the uploaded file
    • error: In case of any error while uploading, this variable gets the appropriate error message
  • Through the inner if statement, we checked whether the file upload in PHP was successful or not.
  • We then use the multi-dimensional $_Files array that holds the information as discussed above.
  • We then figured out the file’s extension and matched it with the allowed types.
  • Next, we removed all the additional spaces from the file.
  • After cleaning the file data, we used the move_uploaded_file function to transfer the file to the desired location.
  • In the end, we wrote the success and error messages that would be fetched and shown by the error variable discussed earlier.

How Both Files Work Together to Enable File Upload in PHP

When both the files are in place, run the webserver to see the file upload in action. In the beginning, you will see the HTML form that we have created in the ‘index.php’ file. This will allow you to choose a file.

File_Upload_in_PHP_1

Ensure selecting a file with an acceptable extension. For this example, let’s choose a ‘png’ file.

File_Upload_in_PHP_2

Once you select the file, you can click on the “Upload the File” button. This will initiate the file upload in PHP. When the form is submitted, the file transfer will take place. If everything goes well, you will see the success message. But if an error occurs, you will see a relevant error message.

File_Upload_in_PHP_3

Once the upload is successful, you will be able to see the uploaded file in the target directory, set to 'C:\xampp\htdocs\test' in the above code. You can set it to anything according to your preference.

File_Upload_in_PHP_4

Note: The name of the file will be changed.

Learn From The Best Mentors in the Industry!

Automation Testing Masters ProgramExplore Program
Learn From The Best Mentors in the Industry!

Resolving the Common Errors That May Be Encountered While a File Upload in PHP

Although file upload in PHP is easy, you may encounter some common errors. The error messages will give you a hint about what error has occurred during the upload. However, you can use the below code to get the exact and detailed reason.

$_Files[‘uploadedFile’][‘error’]

Here are some standard errors that you may face.

The File Is Too Large

You may face UPLOAD_ERR_INI_SIZE or UPLOAD_ERR_FROM_SIZE errors if the size of the selected file is larger than the specified limits. You can easily conquer the error by changing the configuration of the maximum file size key.

Temporary Folder is Missing

Sometimes you can encounter two types of folder errors. The first one is the UPLOAD_ERR_NO_TMP_DIR error thrown if the temporary folder to hold the uploaded files is missing. You will see the UPLOAD_ERR__NO_FILE error if no file is selected to be uploaded.

Partial Upload

The UPLOAD_ERR_PARTIAL error is thrown if the server is not able to upload the file completely.

Can’t Write to Disk

You will get the UPLOAD_ERR_CANT_WRITE error when the server cannot write the file to the disk for whatever reason.

A PHP Extension Stopped the File Upload

You will get the UPLOAD_ERR_EXTENSION if the upload is halted due to any extension error. Finding the actual extension that caused the error might be tricky here, especially if you have uploaded multiple files with different extensions.

Conclusion

In this article, you learned everything about file upload in PHP with a simple example. You have also seen how to create client-side and server-side scripts to enable the file upload in PHP. Now, you can go ahead and try to upload multiple files with different file extensions and see how it goes. Also, attempt getting some errors intentionally to see how the error variable fetches and displays the relevant error message. If you are keen to learn some other fundamental concepts of PHP programming, you can refer to our PHP Tutorial. The tutorials will help you get acquainted with the basic concepts. If you want to go beyond that and become a PHP developer, you can opt for Simplilearn’s PHP Training Course.

Along with complete training and hands-on practical knowledge, you also get a certification upon completing the course. You can further opt for our Complete Web Development Career Bundle. It offers you training for various programming languages, IDEs, and tools used for web development. To put it simply, the course is well adept at helping you excel in web development. That’s the end of our file upload in PHP tutorial article.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449