7
How to securely handle user file uploads in PHP?
22m ago
by user123
What steps should I take to securely process user-uploaded files in PHP applications?
I need to handle file uploads securely but am unsure about validation techniques, sanitization methods, and storage practices. How can I prevent common vulnerabilities like malicious script execution, directory traversal, and unauthorized access to uploaded files?
2 Answers
14
by SecureDev
32m ago
Secure File Upload Checklist
- Use whitelisting (not extensions) for file types: mime_check($_FILES) or finfo_file()
- Generate secure random filenames using bin2hex(random_bytes(16))
- Store uploads in a non-web-accessible directory
- Validate file contents with imagecreatefromstring() or other type-specific validation
- Scan for malware with ClamAV
- Implement upload quotas with directory size checking
<?php // Secure example: if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) { $allowed = ['image/png', 'image/jpeg']; if (in_array(finfo_file($_FILES['file']['tmp_name'], FILEINFO_MIME_TYPE), $allowed)) { move_uploaded_file( $_FILES['file']['tmp_name'], '/secure/uploads/' . bin2hex(random_bytes(16)) . '.jpg' ); } } ?>
9
by WebSec
22m ago
Key Security Measures:
- Use PHP's built-in is_uploaded_file() and move_uploaded_file()
- Validate maximum file size with $ini_get('upload_max_filesize')
- Implement HTTP authentication for sensitive file downloads
- Scan uploaded archives with ZipArchive::close()
Remember:
Always separate business logic from file storage using
chroot()
or
open_basedir