Secure PHP File Upload: MIME Validation, Extension Checks, Size Limits, Filename Sanitization, and Directory Permissions
This article explains common security risks of file uploads in web applications and provides PHP code examples for MIME type validation, extension checking, size limits, filename sanitization, directory permission settings, and safe renaming to mitigate attacks.
File upload functionality is common in many web applications, but it introduces security risks that must be mitigated; this article discusses typical vulnerabilities and offers PHP code snippets with comments to prevent them.
1. Valid MIME type verification – Use $_FILES['file']['type'] to obtain the uploaded file's MIME type and compare it against an allowed list.
<code>$allowedTypes = array('image/jpeg', 'image/png');
if (in_array($_FILES['file']['type'], $allowedTypes)) {
// MIME type is allowed – process upload
} else {
// MIME type is not allowed – abort and show error
}</code>2. File extension verification – Use pathinfo() to extract the file extension and compare it with permitted extensions.
<code>$allowedExtensions = array('jpg', 'png');
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (in_array($extension, $allowedExtensions)) {
// Extension is allowed – process upload
} else {
// Extension is not allowed – abort and show error
}</code>3. File size verification – Retrieve the size via $_FILES['file']['size'] and ensure it does not exceed a defined maximum.
<code>$maxSize = 1024 * 1024; // 1 MB
if ($_FILES['file']['size'] <= $maxSize) {
// Size is acceptable – process upload
} else {
// Size exceeds limit – abort and show error
}</code>4. Filename sanitization – Remove potentially dangerous characters from the original filename before saving.
<code>$filename = $_FILES['file']['name'];
$filename = preg_replace("/[^a-zA-Z0-9._-]/", "", $filename);
</code>5. Directory permission settings – Ensure the upload directory is non‑executable and owned by the web‑server user.
<code>$uploadDir = '/path/to/upload/directory';
chmod($uploadDir, 0755); // set permissions to 0755
chown($uploadDir, 'www-data'); // set owner to web‑server user
</code>6. File renaming – Generate a unique filename to avoid bypassing validation checks and move the uploaded file to its final location.
<code>$filename = uniqid() . '.' . $extension;
$destination = $uploadDir . '/' . $filename;
move_uploaded_file($_FILES['file']['tmp_name'], $destination);
</code>Conclusion – While these measures significantly improve the security of file uploads, they represent basic best practices; developers should perform additional threat modeling, testing, and hardening based on their specific application requirements.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.