What are the best practices for error handling and validation when dealing with file types and MIME types in PHP?

When dealing with file types and MIME types in PHP, it is important to validate the file type before processing it to prevent security vulnerabilities and unexpected behavior. One common approach is to use the `finfo_file` function to check the MIME type of the file and compare it against a list of allowed MIME types. Additionally, it is recommended to handle errors gracefully by using try-catch blocks and providing informative error messages to the user.

// Validate file type and MIME type
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
$filePath = 'path/to/file.jpg';

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $filePath);
finfo_close($finfo);

if (!in_array($mimeType, $allowedMimeTypes)) {
    throw new Exception('Invalid file type. Only JPEG, PNG, and GIF images are allowed.');
}

// Process the file
// Your code to handle the file