In the provided PHP code for file uploads, what best practices should be followed to ensure security and efficiency?
To ensure security and efficiency in file uploads, it is important to validate file types, limit file size, and store files in a secure directory outside the web root. Additionally, consider implementing measures such as renaming files to prevent overwriting and using server-side validation to further enhance security.
// Validate file type
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($extension, $allowedTypes)) {
die('Invalid file type.');
}
// Limit file size
$maxSize = 5 * 1024 * 1024; // 5MB
if ($_FILES['file']['size'] > $maxSize) {
die('File is too large.');
}
// Store file in secure directory
$uploadDir = '/var/www/uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
echo 'File uploaded successfully.';
} else {
echo 'Error uploading file.';
}