What are the best practices for utilizing the finfo class in PHP for MIME type detection?

When utilizing the finfo class in PHP for MIME type detection, it is important to ensure that the file being checked actually exists before trying to detect its MIME type. This can prevent errors and improve the reliability of the detection process. Additionally, specifying the MIME type detection mode can help ensure accurate results.

$file = 'example.txt';

if (file_exists($file)) {
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime_type = $finfo->file($file);
    
    echo "MIME type of $file is: $mime_type";
} else {
    echo "File does not exist.";
}