PHP File Upload


Uploading files is a common requirement in web applications. Whether you are allowing users to upload profile pictures, documents, or media files, PHP provides a robust and secure way to handle file uploads.

This tutorial explains how to create a file upload form, process uploaded files, validate them, and store them on the server safely.

How File Uploads Work in PHP

When a user submits a file through an HTML form:

  1. The file is sent to the server via HTTP POST.

  2. PHP stores it temporarily in a temporary directory.

  3. You can move it to a permanent location using move_uploaded_file().

PHP uses the $_FILES superglobal array to access uploaded files. This array contains information like:

  • name – original filename

  • type – MIME type of the file

  • tmp_name – temporary file path

  • error – error code

  • size – file size in bytes

Creating a File Upload Form

First, you need an HTML form with enctype="multipart/form-data".

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select file to upload: 
    <input type="file" name="profile_pic"><br><br>
    <input type="submit" value="Upload File" name="submit">
</form>
  • The enctype attribute is required for file uploads.

  • The name attribute of the input is used to access the file in PHP.

Handling File Upload in PHP

In upload.php, you can process the uploaded file.

<?php
if(isset($_POST['submit'])) {
    $fileName = $_FILES['profile_pic']['name'];
    $fileTmp = $_FILES['profile_pic']['tmp_name'];
    $uploadDir = "uploads/";

    if(move_uploaded_file($fileTmp, $uploadDir . $fileName)) {
        echo "File uploaded successfully: " . $fileName;
    } else {
        echo "Failed to upload file.";
    }
}
?>
  • move_uploaded_file() moves the file from the temporary directory to a permanent location.

  • Vrinda can now upload her profile picture and store it in the uploads folder.

Validating Uploaded Files

It is important to validate files to prevent security risks.

  1. Check file size

if($_FILES['profile_pic']['size'] > 1048576) { // 1 MB
    die("File is too large!");
}
  1. Check file type

$allowedTypes = ['image/jpeg', 'image/png'];
if(!in_array($_FILES['profile_pic']['type'], $allowedTypes)) {
    die("Only JPEG or PNG files are allowed.");
}
  1. Rename files to avoid conflicts

$newName = time() . "_" . $_FILES['profile_pic']['name'];
move_uploaded_file($_FILES['profile_pic']['tmp_name'], "uploads/" . $newName);
  • Using time() ensures that each file has a unique name.

  • Ananya can now upload multiple files without overwriting previous ones.

Creating the Upload Directory

Make sure the uploads directory exists and has proper permissions.

<?php
if(!is_dir("uploads")) {
    mkdir("uploads", 0755, true);
}
?>
  • 0755 gives read/write/execute permissions to the owner and read/execute permissions to others.

  • This ensures Riya’s uploads are stored safely.

Handling Upload Errors

PHP provides error codes in $_FILES['profile_pic']['error'].

Error Code Description
0 No error, file uploaded successfully
1 File exceeds upload_max_filesize in php.ini
2 File exceeds MAX_FILE_SIZE in HTML form
3 File partially uploaded
4 No file was uploaded
6 Missing temporary folder
7 Failed to write file to disk
8 File upload stopped by PHP extension

Example:

<?php
if($_FILES['profile_pic']['error'] !== 0) {
    die("Error uploading file. Error code: " . $_FILES['profile_pic']['error']);
}
?>

Example: Multiple File Uploads

You can allow multiple files by using multiple in the form and looping through $_FILES.

<form action="upload_multiple.php" method="post" enctype="multipart/form-data">
    Select files to upload:
    <input type="file" name="files[]" multiple><br><br>
    <input type="submit" value="Upload Files">
</form>
<?php
if(isset($_FILES['files'])) {
    foreach($_FILES['files']['tmp_name'] as $key => $tmpName) {
        $fileName = $_FILES['files']['name'][$key];
        move_uploaded_file($tmpName, "uploads/" . $fileName);
        echo "Uploaded: " . $fileName . "<br>";
    }
}
?>
  • Vrinda can now upload several images at once.

  • Each file is moved to the uploads directory safely.

Best Practices for File Uploads

  1. Validate file type and size to prevent malicious uploads.

  2. Rename uploaded files to avoid conflicts and security issues.

  3. Store files outside the web root if they are sensitive.

  4. Set correct permissions on upload directories.

  5. Check PHP configuration (upload_max_filesize and post_max_size) to allow larger files.

  6. Handle errors gracefully to provide user-friendly messages.

Summary of the Tutorial

PHP makes file uploading straightforward and flexible. You learned how to:

  • Create an HTML form for file uploads

  • Access uploaded files via $_FILES

  • Move files from temporary to permanent directories using move_uploaded_file()

  • Validate file size and type

  • Rename files to prevent overwriting

  • Handle upload errors

  • Upload multiple files safely

Using these techniques, Vrinda, Ananya, and Riya can create dynamic applications like profile uploads, content management systems, and media galleries, while keeping the server secure.


Practice Questions

  1. Create an HTML form to upload a single file and process it in PHP, saving it in an uploads folder.

  2. Validate the uploaded file to allow only JPEG and PNG images.

  3. Limit the uploaded file size to 1 MB and display an error if exceeded.

  4. Rename the uploaded file using time() to avoid overwriting existing files.

  5. Check if the uploads directory exists and create it if it doesn’t.

  6. Handle file upload errors using $_FILES['file']['error'] and display appropriate messages.

  7. Create a form that allows uploading multiple files and save each file in the uploads folder.

  8. Display a confirmation message listing all successfully uploaded files.

  9. Restrict users from uploading executable files for security purposes.

  10. Log each uploaded file’s name and upload time into a text file named upload_log.txt.


Go Back Top