English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

PHP File Upload

In this tutorial, you will learn how to use PHP to upload files to a remote web server.

Upload files using PHP

In this tutorial, we will learn how to use a simple HTML form and PHP to upload files to a remote server. You can upload any type of file, such as images, videos, ZIP files, Microsoft Office documents, PDF, executable files, and various other file types.

The1Step: Create an HTML form to upload files

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

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8>
    <title>File Upload Form</title>
</head>
    <form action="upload-manager.html" method="post" enctype="multipart/form-data">
        <h2>Upload File</h2>
        <label for="fileSelect">Filename:</label>
        <input type="file" name="photo" id="fileSelect">
        <input type="submit" name="submit" value="Upload">
        <p><strong>Note:</strong>Only .jpg, .jpeg, .gif, .png formats are allowed, with a maximum size of5 MB.</p>
    </form>
</html>

Note:In addition tofile selectionfields, in addition toHTTP postmethod, and it must include an enctype="multipart/form-data" attribute. This attribute ensures that the form data is encoded as multi-part MIME data, which is necessary for uploading large amounts of binary data (such as images, audio, video, etc.).

The2Step: Process the uploaded file

Below is our "Upload-The complete code of the "manager.php" file. It will permanently store the uploaded files in the "upload" folder and perform some basic security checks, such as file type and file size, to ensure that the user uploads the correct file type and within the allowed limits.

<?php
//Check if the form has been submitted
if ($_SERVER['REQUEST_METHOD'] == "POST") {
    // Check if the file upload was successful
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
        $allowed = array("jpg" => "image"}/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];
    
        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
    
        // Verify file size-Maximum5MB
        $maxsize = 5 * 1024 * 1024;
        if($filesize > $maxsize) die("Error: File size exceeds the allowed limit.");
    
        // Verify the file MIME type
        if(in_array($filetype, $allowed)){
            // Check whether the file exists before uploading it
            if(file_exists("upload/" . $filename)){
                echo $filename . " already exists.";
            } else {
                move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename);
                echo "Your file has been uploaded successfully.";
            } 
        } else {
            echo "Error: There was a problem uploading your file. Please try again."; 
        }
    } else {
        echo "Error: " . $_FILES["photo"]["error"];
    }
}
?>

Note:The above script prevents uploading a file with the same name as an existing file in the same folder. However, if you want to allow this, just add a random string or timestamp at the beginning of the filename, for example $filename = time() . '_' . $_FILES["photo"]["name"];

You may be wondering what this code is about. Well, let's go through each part of this example code one by one to better understand the process.

Explanation of the usage of the code

Once the form is submitted, information about the uploaded file can be accessed through the PHP superglobal array $_FILES. For example, our upload form contains a file selection field named photo (i.e., name = "photo"), if any user uploads a file using this field, we can obtain its details, such as name, type, size, temporary name, or any errors that occur when trying to upload, as shown below:

  • $_FILES["photo"]["name"] — This array value specifies the original name of the file, including the file extension. It does not include the file path.

  • $_FILES["photo"]["type"] — This array value specifies the MIME type of the file.

  • $_FILES["photo"]["size"] — This array value specifies the file size in bytes.

  • $_FILES["photo"]["tmp_name"] — This array value specifies the temporary name, including the complete path assigned to the file after it is uploaded to the server.

  • $_FILES["photo"]["error"] — This array value specifies the error or status code related to file upload, for example, 0 if there is no error.

The PHP code in the following example will only display the details of the uploaded file and store it in the temporary directory on the web server.

<?php
if($_FILES["photo"]["error"] > 0) {
    echo "Error: " . $_FILES["photo"]["error"] . "<br>";
} else {
    echo "File name: " . $_FILES["photo"]["name"] . "<br>";
    echo "File type: " . $_FILES["photo"]["type"] . "<br>";
    echo "File size: " . ($_FILES["photo"]["size"] / 1024) . " KB<br>";
    echo "Stored in: " . $_FILES["photo"]["tmp_name"];
}
?>

Tip:After the file is successfully uploaded, the file will be automatically stored in the temporary directory on the server. To permanently store this file, you need to use the PHP move_uploaded_file() function to move it from the temporary directory to the permanent location.