What are best practices for validating file types and sizes in PHP when uploading files through a form?
When uploading files through a form in PHP, it is important to validate the file type and size to ensure security and prevent potential issues. This can be done by checking the file type using the `$_FILES` superglobal and comparing it against a list of allowed file types. Additionally, the file size can be checked against a maximum limit to prevent large files from being uploaded.
// Validate file type
$allowedFileTypes = ['jpg', 'jpeg', 'png', 'pdf'];
$uploadedFileType = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($uploadedFileType, $allowedFileTypes)) {
echo "Invalid file type. Please upload a JPG, JPEG, PNG, or PDF file.";
exit;
}
// Validate file size
$maxFileSize = 5 * 1024 * 1024; // 5MB
if ($_FILES['file']['size'] > $maxFileSize) {
echo "File is too large. Please upload a file smaller than 5MB.";
exit;
}
// Proceed with file upload
// Move uploaded file to desired directory