What are the best practices for handling file extensions and file sizes in PHP file uploads?
When handling file uploads in PHP, it is important to validate file extensions to prevent malicious files from being uploaded. Additionally, it is recommended to limit the file size to prevent large files from overwhelming the server. One way to achieve this is by using the '$_FILES' superglobal array to access information about the uploaded file, including the file extension and size.
// Validate file extension
$allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');
$uploadedFileExtension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($uploadedFileExtension, $allowedExtensions)) {
echo "Invalid file extension. Please upload a JPG, JPEG, PNG, or GIF file.";
exit;
}
// Limit file size
$maxFileSize = 5 * 1024 * 1024; // 5MB
if ($_FILES['file']['size'] > $maxFileSize) {
echo "File size exceeds the limit of 5MB. Please upload a smaller file.";
exit;
}
// Process file upload
// Your code to move the uploaded file to the desired location