5
votes
How to securely handle user file uploads in PHP?
php
security
file-upload
9087654
modified 1 hour ago
2 Answers
Use secure practices when handling file uploads to prevent malicious activities such as file system manipulation or malicious code execution. Follow these steps:
- Validate uploaded files using
$_FILES['userfile']['type']
to ensure they are of a safe type. - Sanitize the file name and store files in a non-public directory.
- Generate a unique name using
bin2hex(random_bytes(16))
. - Limit access so that users can only see their own files.
Here's an example code snippet:
$filename = bin2hex(random_bytes(16)) . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$directory = 'uploads/';
$upload = ($directory . $filename);
move_uploaded_file($_FILES['file']['tmp_name'], $upload);
You should also consider:
- Implementing a virus scanning service such as ClamAV before saving.
- Limiting file upload sizes and types.
- Using a WAF or similar technology to detect suspicious patterns.
Here’s an example of how you should do it:
// Example PHP Upload Code
$allowed_mime_types = ['image/png', 'image/jpeg'];
if (!in_array($_FILES['file']['type'], $allowed_mime_types)) {
die("Invalid filetype.");
}