Skip to content

File Uploading and Downloading

In PHP, handling file uploads and downloads involves several steps, including setting up an HTML form for file uploads, handling the file on the server side, and setting appropriate headers for file downloads. Let’s explore both in detail with examples.


1. File Uploading in PHP

Step 1: Create an HTML Form

To upload a file, you first need an HTML form with the enctype="multipart/form-data" attribute, which allows file data to be sent in the HTTP request.

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="file">Choose a file to upload:</label>
        <input type="file" name="file" id="file">
        <button type="submit" name="upload">Upload</button>
    </form>
</body>
</html>

Step 2: Handling the Upload in PHP

Once the form is submitted, the file data is accessible through the $_FILES superglobal. You can move the file to a designated directory using move_uploaded_file().

phpCopy code<?php
if (isset($_POST['upload'])) {
    $uploadDirectory = "uploads/";
    $file = $_FILES['file'];
    
    $fileName = basename($file['name']); // Original file name
    $fileTmpName = $file['tmp_name'];    // Temporary file name
    $fileSize = $file['size'];
    $fileError = $file['error'];

    // Check for errors
    if ($fileError === 0) {
        // Ensure the upload directory exists
        if (!is_dir($uploadDirectory)) {
            mkdir($uploadDirectory, 0777, true);
        }
        
        // Define upload path
        $uploadPath = $uploadDirectory . $fileName;
        
        // Move the file to the upload directory
        if (move_uploaded_file($fileTmpName, $uploadPath)) {
            echo "File uploaded successfully: " . $uploadPath;
        } else {
            echo "Failed to move the uploaded file.";
        }
    } else {
        echo "Error occurred during file upload. Error code: " . $fileError;
    }
} else {
    echo "No file uploaded.";
}
?>

Validating the Uploaded File

Before saving a file, it’s best to validate it for:

  • Size: Limit file size to prevent large uploads.
  • Type: Allow only certain file types (e.g., jpg, png, pdf).

Example of Basic Validation

phpCopy code<?php
if ($fileSize > 2 * 1024 * 1024) { // Size limit (2 MB)
    echo "File size exceeds 2 MB.";
    exit();
}

$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
if (!in_array($file['type'], $allowedTypes)) {
    echo "Invalid file type. Only JPG, PNG, and PDF files are allowed.";
    exit();
}
?>

2. File Downloading in PHP

To serve a file for download, set specific headers so the browser knows it should download the file rather than display it.

Basic File Download Script

This script sets headers and uses readfile() to output the file content to the user.

phpCopy code<?php
$file = 'uploads/sample.pdf'; // Path to the file

if (file_exists($file)) {
    // Set headers
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));

    // Output the file content
    readfile($file);
    exit;
} else {
    echo "File not found.";
}
?>

Explanation of the Headers Used

  1. Content-Description: File Transfer: Tells the browser that the response contains a file.
  2. Content-Type: application/octet-stream: Forces a download prompt in the browser.
  3. Content-Disposition: attachment; filename="...": Specifies the file name to be used for the download.
  4. Content-Length: Sets the file size for download.

Note: Always validate and sanitize file paths to avoid exposing sensitive files unintentionally.

Download Files Based on User Input

You can allow users to specify which file to download by adding a form to select the file. Here’s an example with a dropdown list for file selection:

HTML Form for File Selection

htmlCopy code<form action="download.php" method="get">
    <label for="file">Select a file to download:</label>
    <select name="file" id="file">
        <option value="sample.pdf">Sample PDF</option>
        <option value="image.jpg">Image JPG</option>
    </select>
    <button type="submit">Download</button>
</form>

PHP Script to Handle Download

phpCopy code<?php
if (isset($_GET['file'])) {
    $file = 'uploads/' . basename($_GET['file']); // Sanitize input

    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    } else {
        echo "File not found.";
    }
} else {
    echo "No file specified.";
}
?>

Security Considerations

  1. Restrict File Types: Only allow specific file types during upload to prevent malicious files.
  2. Sanitize File Names: Use basename() to prevent directory traversal attacks.
  3. Limit File Size: Set maximum file size limits to prevent large uploads.
  4. Access Control: Only allow authorized users to upload or download files, if needed.

Summary

  • File Uploading: Use an HTML form with enctype="multipart/form-data" and handle the upload in PHP using move_uploaded_file().
  • File Downloading: Use header() to set headers and readfile() to serve files for download.
  • Security: Sanitize file names, restrict file types, and control file sizes to ensure secure uploads and downloads.

These methods offer a reliable way to manage file uploads and downloads in PHP applications, allowing you to handle file operations with efficiency and security.