In what ways can PHP developers prevent their applications from crashing when attempting to verify the MIME type of uploaded files?

When attempting to verify the MIME type of uploaded files in PHP, developers can prevent their applications from crashing by using a combination of file extension checks and MIME type validation. This involves checking the file extension against a whitelist of allowed extensions and then verifying the MIME type using PHP's finfo_file function. By implementing both checks, developers can ensure that only valid files are processed, reducing the risk of crashes due to malicious or incorrect file uploads.

$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
$file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if (!in_array($file_extension, $allowed_extensions)) {
    // Handle invalid file extension
    die('Invalid file extension.');
}

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $_FILES['file']['tmp_name']);
finfo_close($finfo);

if ($mime_type !== 'image/jpeg' && $mime_type !== 'image/png' && $mime_type !== 'image/gif') {
    // Handle invalid MIME type
    die('Invalid MIME type.');
}

// Proceed with file processing