PHP

Securely Handle File Uploads in PHP to Prevent Malicious Injections

Learn to implement secure file uploads in PHP, including validation of file types, sizes, and proper storage to prevent arbitrary code execution and directory traversal vulnerabilities.

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['uploadFile'])) {
    $uploadDir = '/var/www/uploads/'; // Store outside web root if possible
    $allowedMimeTypes = ['image/jpeg', 'image/png', 'application/pdf'];
    $maxFileSize = 2 * 1024 * 1024; // 2MB

    $file = $_FILES['uploadFile'];
    $fileName = basename($file['name']);
    $fileTmpName = $file['tmp_name'];
    $fileSize = $file['size'];
    $fileError = $file['error'];
    $fileType = mime_content_type($fileTmpName); // Use mime_content_type for true type

    if ($fileError !== UPLOAD_ERR_OK) {
        die("Upload error: " . $fileError); 
    }

    if ($fileSize > $maxFileSize) {
        die("File is too large.");
    }

    if (!in_array($fileType, $allowedMimeTypes)) {
        die("Invalid file type. Allowed types: " . implode(', ', $allowedMimeTypes));
    }

    // Generate a unique file name to prevent overwriting and path traversal
    $newFileName = uniqid('', true) . '.' . pathinfo($fileName, PATHINFO_EXTENSION);
    $destination = $uploadDir . $newFileName;

    if (move_uploaded_file($fileTmpName, $destination)) {
        echo "File uploaded successfully: " . htmlspecialchars($newFileName);
    } else {
        echo "Failed to move uploaded file.";
    }
} else {
    echo '<form action="" method="post" enctype="multipart/form-data">
            <input type="file" name="uploadFile">
            <button type="submit">Upload</button>
          </form>';
}

?>
How it works: This PHP snippet demonstrates secure file upload handling. It performs crucial server-side validations: checking for upload errors, enforcing a maximum file size, and verifying the true MIME type (using `mime_content_type`) against an allowlist to prevent malicious file types. It also generates a unique filename to avoid path traversal and overwriting existing files, and suggests storing uploads outside the web root for enhanced security, preventing direct execution.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs