What are alternative methods for checking file formats in PHP if MIME types are not reliable?

When MIME types are not reliable for checking file formats in PHP, an alternative method is to use file signatures or magic numbers. File signatures are unique sequences of bytes located at the beginning of a file that can be used to determine its format. By reading these signatures, we can accurately identify the file type regardless of its MIME type.

function getFileFormat($filename) {
    $file = fopen($filename, 'r');
    $signature = fread($file, 4); // Read the first 4 bytes
    fclose($file);

    // Check file signatures to determine file format
    if ($signature == "\xFF\xD8\xFF\xE0" || $signature == "\xFF\xD8\xFF\xE1") {
        return 'image/jpeg';
    } elseif ($signature == "\x89\x50\x4E\x47") {
        return 'image/png';
    } elseif ($signature == "GIF8") {
        return 'image/gif';
    } else {
        return 'unknown';
    }
}

$filename = 'example.jpg';
$fileFormat = getFileFormat($filename);
echo "File format: $fileFormat";