6
How to prevent directory traversal attacks when handling file uploads in PHP?
Asked 5 hours ago
by user2222226
I'm implementing a file upload system in PHP and want to ensure it's secure from path traversal attacks. What's the recommended way to sanitize and validate uploaded filenames to prevent users from uploading files like ../../malicious.php that could be placed in unsafe directories?
My current approach moves uploaded files to a /uploads directory, but I'm unsure if this is sufficient:
$filename = basename($_FILES['upload']['name']);
move_uploaded_file($_FILES['upload']['tmp_name'], 'uploads/' . $filename);
3 Answers
14 votes
by SecurityPro
answered 4 hours ago
Use multiple layers of validation:
- Always validate and sanitize filenames with
basename()
and custom checks - Add UUID as a prefix/suffix to uploaded filenames
- Store files outside the web root
$safe_name = substr(sha1(microtime()), 0, 8) . '_' . basename($filename);
11 votes
by CodeGuard
answered 2 hours ago
Add these security layers:
- Check for PHP extensions in filenames with regex
- Use a dedicated uploads directory with strict .htaccess rules
- Implement rate limiting
if (preg_match('/\\.|\\.\\.\\./', $filename)) {
die('Invalid filename');
}