What best practices should be followed when handling file uploads in PHP to avoid server security issues?
File uploads in PHP can pose security risks if not handled properly. To avoid these issues, it is important to validate file types, limit file sizes, store files outside of the web root directory, and sanitize file names to prevent directory traversal attacks.
// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
die('Invalid file type.');
}
// Limit file size
$maxSize = 10 * 1024 * 1024; // 10MB
if ($_FILES['file']['size'] > $maxSize) {
die('File is too large.');
}
// Store files outside of web root directory
$uploadDir = '/var/www/uploads/';
move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $_FILES['file']['name']);
// Sanitize file name
$fileName = preg_replace("/[^A-Za-z0-9_.]/", '', $_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $fileName);