Secure File Uploads in PHP
File uploads are a common feature, but accepting files from visitors introduces security and storage risks. Never trust the filename, extension, or MIME type supplied by the browser.
Create the HTML Form
The form must use multipart/form-data and a file input.
<form method="post" enctype="multipart/form-data">
<input type="file" name="document" required>
<button type="submit">Upload</button>
</form>
The server must still validate every upload. Browser-side restrictions are only a user experience aid.
Validate the Upload
Check the upload error code and enforce a size limit. Use PHP's Fileinfo extension to inspect the detected MIME type, then compare it against a strict allowlist.
$file = $_FILES["document"] ?? null;
if (!$file || $file["error"] !== UPLOAD_ERR_OK) {
throw new RuntimeException("Upload failed.");
}
$maxBytes = 5 * 1024 * 1024;
if ($file["size"] > $maxBytes) {
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.");
}
The accepted MIME types should match the feature's real requirements. Additional format-specific validation may be necessary.
Use a Generated Filename
Do not use the visitor's original filename as the storage path. Generate a random name and use the extension selected from the server-side allowlist.
$filename = bin2hex(random_bytes(16)) . "." . $allowed[$mime];
$destination = $privateUploadDirectory . "/" . $filename;
if (!move_uploaded_file($file["tmp_name"], $destination)) {
throw new RuntimeException("Could not store uploaded file.");
}
Store uploads outside the public web root whenever possible. If public access is required, serve files through a controlled download endpoint.
Additional Protections
Set upload limits in PHP configuration, prevent executable files from being served, apply access controls, scan files when appropriate, and remove temporary files according to a retention policy. Consider CSRF protection for authenticated upload forms.
Conclusion
A secure upload workflow validates the server-side file type and size, generates its own filename, and stores files in a controlled location. Treat every uploaded file as untrusted.