Table of contents
1.
Introduction
2.
Configure The "php.ini" File
2.1.
Example Configuration
3.
PHP $_FILES
4.
move_uploaded_file() function
5.
Create The HTML Form
6.
Create The Upload File PHP Script
7.
Check if File Already Exists
7.1.
Limit File Size
7.2.
Limit File Type
8.
Complete Upload File PHP Script
9.
Frequently Asked Questions
9.1.
How do I upload multiple files at once in PHP?
9.2.
What happens if I don’t check for file type and size?
9.3.
How can I change the maximum file size allowed for uploads?
10.
Conclusion
Last Updated: Dec 28, 2024
Easy

Introduction to PHP File Upload

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

PHP makes it easy to upload both single and multiple files with just a few lines of code.

The file upload feature in PHP supports uploading text and binary files seamlessly. Additionally, PHP provides robust control over the upload process using authentication and file handling functions, ensuring secure and efficient file management.

Introduction to PHP File Upload

In this article, we’ll guide you through the process of uploading files using PHP, from configuring the PHP environment to writing the necessary code for uploading and validating files. You will learn how to ensure security and proper functionality when uploading files to your web server.

Configure The "php.ini" File

The first step in allowing file uploads in PHP is to configure the php.ini file, which is the configuration file for PHP. This file controls many important settings for PHP, including those related to file uploads.

To enable file uploads, make sure the following settings are correct in your php.ini file:

  1. file_uploads: This setting must be enabled. If it is set to "Off", file uploads are disabled.
  2. upload_max_filesize: This defines the maximum allowed size for uploaded files.
  3. post_max_size: This defines the maximum size of data that can be sent to the server, which should be larger than the file size you allow for uploads.
  4. max_file_uploads: This defines the maximum number of files that can be uploaded simultaneously.

Example Configuration

file_uploads = On
upload_max_filesize = 10M
post_max_size = 20M
max_file_uploads = 20

 

  • file_uploads: Set to On to allow file uploads.
     
  • upload_max_filesize: Allows uploads up to 10 MB.
     
  • post_max_size: Allows post data up to 20 MB.
     
  • max_file_uploads: Allows uploading a maximum of 20 files in a single request.
     

After making these changes, restart your web server for the changes to take effect.

PHP $_FILES

In PHP, the $_FILES superglobal is used to handle file uploads. It is an associative array that contains information about the uploaded files, such as the file name, type, size, & temporary location on the server. When a file is uploaded via an HTML form with the enctype attribute set to "multipart/form-data", the file data is available in the $_FILES array.

The $_FILES array has a specific structure. For each uploaded file, it contains a sub-array with the following elements:

  • "name": The original name of the uploaded file
     
  • "type": The MIME type of the uploaded file
     
  • "tmp_name": The temporary name of the file on the server
     
  • "error": An error code associated with the file upload
     
  • "size": The size of the uploaded file in bytes
     

By accessing these elements, you can retrieve information about the uploaded file & perform necessary validations & operations.
 

Let’s take an example of how to access the uploaded file information:

if (isset($_FILES['uploadedFile'])) {
    $fileName = $_FILES['uploadedFile']['name'];
    $fileType = $_FILES['uploadedFile']['type'];
    $fileSize = $_FILES['uploadedFile']['size'];
    $fileTmpName = $_FILES['uploadedFile']['tmp_name'];
    $fileError = $_FILES['uploadedFile']['error'];
    
    // Perform further validations & operations
}


In this code snippet, we first check if the 'uploadedFile' key exists in the $_FILES array using the isset() function. If it does, we can access the various elements of the uploaded file using the respective keys.

move_uploaded_file() function


The move_uploaded_file() function in PHP is used to move an uploaded file from its temporary location to a desired destination on the server. It takes two parameters: the source path (the temporary location of the uploaded file) & the destination path (where you want to move the file).

The basic syntax of the move_uploaded_file() function is:

move_uploaded_file($sourcePath, $destinationPath);

 

The function returns true if the file is successfully moved, or false if the move operation fails.

When a file is uploaded, PHP stores it in a temporary directory on the server. The move_uploaded_file() function allows you to move the file from this temporary location to a permanent location of your choice. It is important to note that the destination directory must have the necessary permissions for PHP to write files to it.

Let’s discuss an example of how to use the move_uploaded_file() function:

if (isset($_FILES['uploadedFile'])) {
    $fileTmpName = $_FILES['uploadedFile']['tmp_name'];
    $destinationPath = 'uploads/' . $_FILES['uploadedFile']['name'];
    
    if (move_uploaded_file($fileTmpName, $destinationPath)) {
        echo 'File uploaded successfully.';
    } else {
        echo 'Error uploading the file.';
    }
}


In this code snippet, we first check if the 'uploadedFile' key exists in the $_FILES array. If it does, we retrieve the temporary name of the uploaded file using $_FILES['uploadedFile']['tmp_name']. We then specify the destination path where we want to move the file. In this example, we are moving the file to a directory named 'uploads' with the original file name.

Finally, we use the move_uploaded_file() function to move the file from its temporary location to the specified destination path. If the move operation is successful, it will return true, & we echo a success message. If the move fails, we echo an error message.

Create The HTML Form

Once PHP is configured to handle file uploads, the next step is creating an HTML form that allows users to select a file and upload it.

Here’s a simple HTML form for file uploading:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload File</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="fileToUpload">Choose file to upload:</label>
        <input type="file" name="fileToUpload" id="fileToUpload">
        <input type="submit" value="Upload File" name="submit">
    </form>
</body>
</html>


Output

Output

Explanation:

  • The form element uses the POST method to send data to the server.
     
  • The enctype="multipart/form-data" attribute ensures that the file is properly encoded before being sent.
     
  • The input type="file" creates a file input field, allowing users to select a file from their computer.
     
  • When the form is submitted, it sends the file to upload.php, which we will create next.

Create The Upload File PHP Script

Now, let’s create the PHP script that handles the file upload. The script will process the file uploaded via the form, move it to a specific directory, and handle basic error checking.

<?php
if(isset($_POST['submit'])){
    $target_dir = "uploads/"; // directory to store uploaded files
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }

    // Check if file size is too large
    if ($_FILES["fileToUpload"]["size"] > 500000) { // 500 KB limit
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "gif") {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>
You can also try this code with Online PHP Compiler
Run Code


Explanation:

  • $_FILES is a global array that contains information about the uploaded file.
     
  • The file is moved from its temporary location to the uploads/ directory using move_uploaded_file().
     
  • We perform several checks:
    1. File already exists: Prevents overwriting existing files.
       
    2. File size: Restricts file uploads to files smaller than 500 KB.
       
    3. File type: Only allows image files (JPG, PNG, JPEG, GIF).

Check if File Already Exists

In the script above, we already check if the file exists using the file_exists() function. If a file with the same name already exists in the upload directory, the upload is aborted, and an error message is shown. This prevents overwriting of files with the same name.

Limit File Size

To limit the file size, we use the $_FILES["fileToUpload"]["size"] value, which contains the size of the uploaded file in bytes. In our example, the size limit is set to 500 KB. If the uploaded file exceeds this size, an error message is displayed.

You can change the limit by modifying this check:

if ($_FILES["fileToUpload"]["size"] > 500000) { // 500 KB limit
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

Limit File Type

To limit the types of files that can be uploaded, we use the file’s extension. We check the file type against a list of allowed extensions (JPG, PNG, JPEG, GIF).

if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "gif") {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}


You can add or remove file extensions as per your requirements.

Complete Upload File PHP Script

Combining all the elements, here’s the complete PHP file upload script:

<?php
if(isset($_POST['submit'])){
    $target_dir = "uploads/"; // directory to store uploaded files
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));


    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check if file size is too large
    if ($_FILES["fileToUpload"]["size"] > 500000) { // 500 KB limit
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "gif") {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }


    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>

Frequently Asked Questions

How do I upload multiple files at once in PHP?

To upload multiple files, modify the HTML form by adding multiple to the file input tag. Then, loop through $_FILES in PHP to process each file.

What happens if I don’t check for file type and size?

Without these checks, users could upload unwanted files, like large files or malicious files that could harm your server or application.

How can I change the maximum file size allowed for uploads?

Change the upload_max_filesize and post_max_size values in the php.ini file to adjust the maximum file size.

Conclusion

In this article, we've learned how to implement a basic file upload feature using PHP. We've configured the PHP environment, created an HTML form to select files, and built a PHP script to process and validate the uploads. You should now be able to handle file uploads securely, limit file size and types, and check for errors during the upload process.

You can also check out our other blogs on Code360.

Live masterclass