Application Security

Harden PHP File Uploads Against Malicious Files

Validate upload errors, size, MIME type, and storage location while preventing executable uploads and path traversal.

Validate the upload

if (!isset($_FILES['upload']) ||
    $_FILES['upload']['error'] !== UPLOAD_ERR_OK) {
    throw new RuntimeException('Upload failed.');
}

$file = $_FILES['upload'];

if ($file['size'] > 5 * 1024 * 1024) {
    throw new RuntimeException('File is too large.');
}

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);

$allowed = [
    'application/pdf' => 'pdf',
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
];

if (!isset($allowed[$mime])) {
    throw new RuntimeException('Unsupported file type.');
}

Generate a destination name

$name = bin2hex(random_bytes(16)) . '.' . $allowed[$mime];
$target = '/home/account/private-uploads/' . $name;

if (!move_uploaded_file($file['tmp_name'], $target)) {
    throw new RuntimeException('Could not store upload.');
}

Store files safely

Keep uploads outside the public document root where possible. If public access is needed, serve files through an authorization-aware handler and ensure scripts cannot execute in the storage directory.

Apply request-size limits, quotas, malware scanning where appropriate, and access controls. MIME detection is useful but cannot guarantee a file is harmless.