PHP File Upload: Secure File Upload with Validation (Complete Guide 2026)

By Lyndon Bermoy

Updated on:

PHP File Upload: Secure File Upload with Validation (Complete Guide 2026)

File upload is one of the most commonly misimplemented features in PHP applications. Done wrong, it lets attackers upload PHP files and execute arbitrary code on your server. Done right, it is a secure, reliable feature that handles images, documents, and other user files safely. This guide covers the complete secure file upload implementation.

The $_FILES Superglobal

When a form submits a file, PHP populates $_FILES with information about the upload:

// HTML form:
// <form method="POST" enctype="multipart/form-data">
//   <input type="file" name="profile_image">
//   <button type="submit">Upload</button>
// </form>

// $_FILES structure after submission:
$file = $_FILES['profile_image'];
// [
//   'name'     => 'photo.jpg',        // Original filename from client
//   'type'     => 'image/jpeg',       // MIME type (NOT reliable — user-controlled)
//   'tmp_name' => '/tmp/phpXXXXXX',  // Temporary file on server
//   'error'    => 0,                  // 0 = UPLOAD_ERR_OK
//   'size'     => 143521,             // File size in bytes
// ]

Upload Error Codes

$error_messages = [
    UPLOAD_ERR_INI_SIZE   => 'File exceeds upload_max_filesize in php.ini',
    UPLOAD_ERR_FORM_SIZE  => 'File exceeds MAX_FILE_SIZE in the HTML form',
    UPLOAD_ERR_PARTIAL    => 'File was only partially uploaded',
    UPLOAD_ERR_NO_FILE    => 'No file was uploaded',
    UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
    UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
    UPLOAD_ERR_EXTENSION  => 'Upload blocked by PHP extension',
];

if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    $msg = $error_messages[$_FILES['file']['error']] ?? 'Unknown upload error';
    throw new RuntimeException($msg);
}

Complete Secure Upload Function

function upload_file(array $file, string $upload_dir, array $options = []): string {
    $defaults = [
        'max_size'       => 5 * 1024 * 1024, // 5MB
        'allowed_types'  => ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
        'allowed_ext'    => ['jpg', 'jpeg', 'png', 'gif', 'webp'],
    ];
    $opts = array_merge($defaults, $options);

    // 1. Check upload error
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Upload error code: ' . $file['error']);
    }

    // 2. Verify it is a real uploaded file (prevents path traversal attacks)
    if (!is_uploaded_file($file['tmp_name'])) {
        throw new RuntimeException('Invalid upload — not an HTTP upload');
    }

    // 3. Check file size
    if ($file['size'] > $opts['max_size']) {
        throw new RuntimeException('File too large. Maximum: ' . ($opts['max_size'] / 1048576) . 'MB');
    }

    // 4. Validate MIME type using finfo (NOT $_FILES['type'] — user-controlled)
    $finfo    = new finfo(FILEINFO_MIME_TYPE);
    $mimeType = $finfo->file($file['tmp_name']);
    if (!in_array($mimeType, $opts['allowed_types'], true)) {
        throw new RuntimeException("File type not allowed: $mimeType");
    }

    // 5. Validate extension against original filename
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $opts['allowed_ext'], true)) {
        throw new RuntimeException("File extension not allowed: $ext");
    }

    // 6. Generate a safe, random filename (never use the original name)
    $safe_filename = bin2hex(random_bytes(16)) . '.' . $ext;

    // 7. Ensure the upload directory is outside the web root, or protected
    $dest = rtrim($upload_dir, '/') . '/' . $safe_filename;

    // 8. Move file to destination
    if (!move_uploaded_file($file['tmp_name'], $dest)) {
        throw new RuntimeException('Failed to save file');
    }

    return $safe_filename;
}

Protecting the Upload Directory

# .htaccess in your uploads directory — prevent PHP execution:
<FilesMatch "\.(php|phtml|php3|php4|php5|php7|phar)$">
    Deny from all
</FilesMatch>

Options -ExecCGI
php_flag engine off

The safest approach: store uploaded files outside the web root and serve them through a PHP controller:

// serve-file.php:
$filename = basename($_GET['file'] ?? '');  // basename() prevents directory traversal
$filepath = '/home/user/secure_uploads/' . $filename;

if (!file_exists($filepath) || !is_file($filepath)) {
    http_response_code(404);
    exit;
}

$finfo    = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($filepath);

header('Content-Type: ' . $mimeType);
header('Content-Length: ' . filesize($filepath));
readfile($filepath);

Image-Specific Validation

// Re-process the image to strip any embedded PHP code or malicious metadata:
function sanitize_image(string $tmp_path, string $dest_path, string $mime_type): bool {
    switch ($mime_type) {
        case 'image/jpeg':
            $img = imagecreatefromjpeg($tmp_path);
            return imagejpeg($img, $dest_path, 85);
        case 'image/png':
            $img = imagecreatefrompng($tmp_path);
            return imagepng($img, $dest_path, 8);
        case 'image/gif':
            $img = imagecreatefromgif($tmp_path);
            return imagegif($img, $dest_path);
        case 'image/webp':
            $img = imagecreatefromwebp($tmp_path);
            return imagewebp($img, $dest_path, 85);
        default:
            return false;
    }
}

Re-creating the image via GD strips any hidden PHP code embedded in image metadata (a real attack vector).

READ ALSO:   PHP cURL Tutorial: Make HTTP Requests from PHP (2026 Guide)

Multiple File Upload

<!-- HTML: multiple files -->
<input type="file" name="documents[]" multiple>

<?php
// $_FILES['documents'] is indexed differently for multiple uploads:
$uploaded = [];
for ($i = 0; $i < count($_FILES['documents']['name']); $i++) {
    $file = [
        'name'     => $_FILES['documents']['name'][$i],
        'type'     => $_FILES['documents']['type'][$i],
        'tmp_name' => $_FILES['documents']['tmp_name'][$i],
        'error'    => $_FILES['documents']['error'][$i],
        'size'     => $_FILES['documents']['size'][$i],
    ];
    if ($file['error'] === UPLOAD_ERR_OK) {
        $uploaded[] = upload_file($file, '/uploads/', [
            'allowed_types' => ['application/pdf', 'application/msword'],
            'allowed_ext'   => ['pdf', 'doc', 'docx'],
        ]);
    }
}

Security Checklist

  • [ ] Validate MIME type with finfo — NOT $_FILES['type']
  • [ ] Validate file extension against allowlist (not blocklist)
  • [ ] Enforce maximum file size
  • [ ] Use is_uploaded_file() to verify HTTP upload
  • [ ] Generate random filename — never use original user-provided name
  • [ ] Block PHP execution in upload directory (.htaccess or serve outside web root)
  • [ ] For images: re-process with GD to strip malicious metadata
  • [ ] Store sensitive files outside web root, serve via controller

Frequently Asked Questions

Why should I not trust $_FILES[‘type’]?

The MIME type in $_FILES['type'] is sent by the client browser and can be set to any value. An attacker can upload a PHP file and set the MIME type to image/jpeg. Always use PHP’s finfo extension to detect the actual MIME type from the file content.

How do I increase the PHP upload limit?

In php.ini: set upload_max_filesize = 20M and post_max_size = 25M (post_max_size must be larger). On shared hosting, you can often set these via .htaccess: php_value upload_max_filesize 20M.

Conclusion

Secure file upload requires validating MIME type with finfo (not the client-provided type), checking file extension against a strict allowlist, generating random filenames, and blocking PHP execution in the upload directory. The extra lines of validation code prevent a category of vulnerabilities that has been exploited repeatedly on PHP sites. Never skip the MIME type and extension validation.

Next Step for Your Project Journey

Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

READ ALSO:   How to Use File Uploads in a Real Project
Explore Source Code Continue Tutorials Final Year Projects

Leave a Comment