What best practices should be followed when checking file sizes and types during file uploads in PHP to prevent errors like incorrect MIME types?

When checking file sizes and types during file uploads in PHP, it is important to validate both the file size and MIME type to prevent errors like incorrect file types being uploaded. To do this, you can use PHP functions like `$_FILES['file']['size']` to check the file size and `$_FILES['file']['type']` to check the MIME type. Additionally, you can use functions like `mime_content_type()` to verify the MIME type of the file.

// Check file size
$maxFileSize = 5 * 1024 * 1024; // 5 MB
if ($_FILES['file']['size'] > $maxFileSize) {
    echo "File size is too large. Please upload a file under 5MB.";
    exit;
}

// Check file type
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedMimeTypes)) {
    echo "Invalid file type. Please upload a JPEG, PNG, or GIF file.";
    exit;
}

// Get the actual MIME type of the file
$actualMimeType = mime_content_type($_FILES['file']['tmp_name']);
if (!in_array($actualMimeType, $allowedMimeTypes)) {
    echo "Invalid file type. Please upload a JPEG, PNG, or GIF file.";
    exit;
}

// Proceed with file upload
// Your file upload code here