PHP

Secure File Upload Validation in PHP

Implement secure server-side validation for file uploads in PHP, checking types, sizes, and potential malicious content to prevent various attacks.

<?php

function handleSecureFileUpload(string $fileInputName, string $uploadDir): array
{
    if (!isset($_FILES[$fileInputName]) || $_FILES[$fileInputName]['error'] !== UPLOAD_ERR_OK) {
        return ['success' => false, 'message' => 'No file uploaded or upload error.'];
    }

    $file = $_FILES[$fileInputName];
    $fileName = $file['name'];
    $fileTmpName = $file['tmp_name'];
    $fileSize = $file['size'];
    $fileError = $file['error'];

    // Define allowed file types (MIME types)
    $allowedMimeTypes = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'application/pdf',
    ];

    // Define maximum file size (e.g., 5MB)
    $maxFileSize = 5 * 1024 * 1024; // 5 MB in bytes

    // 1. Check for upload errors
    if ($fileError !== UPLOAD_ERR_OK) {
        return ['success' => false, 'message' => 'File upload failed with error code: ' . $fileError];
    }

    // 2. Validate file size
    if ($fileSize > $maxFileSize) {
        return ['success' => false, 'message' => 'File is too large. Maximum size is ' . ($maxFileSize / 1024 / 1024) . 'MB.'];
    }

    // 3. Validate file type (MIME type) securely
    // Using finfo_open for reliable MIME type detection, not just $_FILES['type']
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $detectedMimeType = finfo_file($finfo, $fileTmpName);
    finfo_close($finfo);

    if (!in_array($detectedMimeType, $allowedMimeTypes)) {
        return ['success' => false, 'message' => 'Invalid file type. Allowed types: ' . implode(', ', array_map(fn($t) => explode('/', $t)[1], $allowedMimeTypes)) . '. Detected: ' . $detectedMimeType];
    }

    // 4. Generate a unique, unpredictable filename to prevent path traversal and overwrite attacks
    $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
    $newFileName = uniqid('upload_', true) . '.' . $fileExtension;
    $destination = rtrim($uploadDir, '/') . '/' . $newFileName;

    // Ensure the upload directory exists and is writable
    if (!is_dir($uploadDir) || !is_writable($uploadDir)) {
        return ['success' => false, 'message' => 'Upload directory does not exist or is not writable.'];
    }

    // 5. Move the uploaded file to its final, secure destination
    if (move_uploaded_file($fileTmpName, $destination)) {
        // Optional: Further processing like image resizing, virus scanning, etc.
        // set correct file permissions
        chmod($destination, 0644);
        return ['success' => true, 'message' => 'File uploaded successfully!', 'filePath' => $destination];
    } else {
        return ['success' => false, 'message' => 'Failed to move uploaded file.'];
    }
}

// Example Usage in a form handler:
// if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//     $uploadDirectory = __DIR__ . '/uploads'; // Make sure this directory exists and is writable
//     $result = handleSecureFileUpload('myFile', $uploadDirectory);
//     echo json_encode($result);
// }
How it works: File upload vulnerabilities are common and can lead to severe compromises. This PHP snippet demonstrates robust server-side validation for uploaded files. It checks for general upload errors, enforces a maximum file size, and critically, validates the file's true MIME type using `finfo_open` to prevent attackers from disguising malicious files. It also generates a unique filename to prevent path traversal or file overwrite attacks and ensures the file is moved to a secure, non-web-accessible directory with appropriate permissions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs