What best practices should be followed when handling file uploads in PHP to prevent website downtime?
When handling file uploads in PHP, it is important to set appropriate limits on file size, ensure proper file type validation, and sanitize file names to prevent security vulnerabilities and potential website downtime. Additionally, using proper error handling techniques and storing uploaded files in a secure location can help maintain the stability of the website.
// Set maximum file size limit to 5MB
define('MAX_FILE_SIZE', 5 * 1024 * 1024);
// Allowed file types
$allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
// Sanitize file name
$filename = preg_replace("/[^A-Za-z0-9.]/", '', basename($_FILES['file']['name']);
// Validate file size
if ($_FILES['file']['size'] > MAX_FILE_SIZE) {
die('File size exceeds limit');
}
// Validate file type
$file_ext = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array($file_ext, $allowed_types)) {
die('Invalid file type');
}
// Move uploaded file to secure directory
$upload_dir = 'uploads/';
$upload_file = $upload_dir . $filename;
if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
die('Failed to upload file');
}