How to securely handle user file uploads in PHP?
I'm implementing a file upload feature in PHP and need to ensure security. What are the best practices for handling file uploads securely?
I understand basic validation like checking file types and sizes, but what steps should I take to prevent malicious files? Should I use a virus scanner or isolate user-uploaded files in a separate directory?
2 Answers
To securely handle file uploads:
-
Whitelist valid file types using
mimetype
verification instead of relying on extensions. -
Obliterate original filenames using
uniqid()
to prevent directory traversal attacks. - Store uploaded files in a non-web-accessible directory to prevent direct execution.
-
Use dedicated security tools like
ClamAV
for virus scanning. - Implement rate limiting to prevent upload abuse.
Security Note: Never trust $_FILES['name']
directly. Always rename files server-side.
Alternative Method Using PHP's File API
$allowed = ['image/png', 'application/pdf'];
if (!in_array($_FILES['upload']['type'], $allowed)) {
die('Invalid file type');}
$newName = bin2hex(random_bytes(16)) . pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);
move_uploaded_file($_FILES['upload']['tmp_name'], "/secure/uploads/$newName");
This ensures: type validation, secure filenames, and stores uploads outside web root.