<?PHP
FUNCTION strhex($string)
{
$hex = "";
$len = STRLEN($string);
FOR($i = 0; $i < $len; ++$i)
{
$hex .= STR_PAD(DECHEX(ORD($string[$i])), 2, 0, STR_PAD_LEFT);
}
RETURN $hex;
}
$data = FILE_GET_CONTENTS($filename);
IF(PREG_MATCH('/\.(jpg|jpeg|gif|png)/i', $filename, $matches))
{
$type = ($matches[1] === 'jpeg') ? 'jpg' : $matches[1];
}
ELSE
{
// Get the first 12 bytes of the file
$hdr = strhex($data[0].$data[1].$data[2].$data[3].$data[4].$data[5].$data[6].$data[7].$data[8].$data[9].$data[10].$data[11]);
ECHO $hdr;
// Match header of the file (Google it).
IF(PREG_MATCH('$/ffd8ffe0....4A46494600/i', $hdr))
{
// JPEG?
$type = 'jpg';
}
ELSEIF(PREG_MATCH('$/89504e470D0a1a0a/i', $hdr))
{
// PNG?
$type = 'png';
}
ELSEIF(PREG_MATCH('$/474946/i', $hdr))
{
// GIF?
$type = 'gif';
}
ELSE
{
// Unknown image type.
}
}