Back to results for “Security”
PHP › Security

Why is validating and sanitizing file uploads important, and what specific checks should you perform to prevent an attacker from uploading a malicious file?

Intermediate

Answer

Allowing users to upload files introduces significant security risk if not carefully validated, since an attacker could attempt to upload a disguised executable script rather than the expected file type, and important checks include verifying the actual file content and its true MIME type rather than trusting the filename extension alone, enforcing a strict maximum file size, generating a new random filename rather than using the user supplied one, and storing uploaded files outside of any directory where PHP scripts could be directly executed.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['photo']['tmp_name']);

if (!in_array($mime, ['image/jpeg', 'image/png'])) {
    die('Invalid file type');
}
Real-world example A profile picture upload feature checks the actual MIME type of every uploaded file using finfo rather than trusting its extension, preventing an attacker from renaming a malicious script file with a fake dot jpg extension and having it accepted as a legitimate image.

Common follow-ups: Why is checking a file's extension alone not sufficient to confirm its actual type?;What additional risks exist if uploaded files are stored within a publicly accessible, script executable directory?