Skip to content

Instantly share code, notes, and snippets.

@abhibeckert
Created December 29, 2013 01:25
Show Gist options
  • Save abhibeckert/8166418 to your computer and use it in GitHub Desktop.
Save abhibeckert/8166418 to your computer and use it in GitHub Desktop.
$imgData = file_get_contents($path);
// determine mime type
$magicNumbersToMimeTypes = array(
'474946383761'=>'image/gif', // GIF87a type gif
'474946383961'=>'image/gif', // GIF89a type gif
'89504E470D0A1A0A'=>'image/png', // png
'FFD8FFE0'=>'image/jpeg', // JFIF jpeg
'FFD8FFE1'=>'image/jpeg', // EXIF jpeg
'FFD8FFE8'=>'image/jpeg', // SPIFF jpeg
);
$signature = strtoupper(array_shift(unpack("H*", substr($imgData,0,60)))); // convert first 60 bytes of $imgData to a hex string
$imgMimeType = 'application/octet-stream';
foreach($magicNumbersToMimeTypes as $magicNumber => $mimeType) {
if (StringUtil::beginsWith($signature, $magicNumber)) {
$imgMimeType = $mimeType;
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment