PHP : binary image data, checking the image type
I have some images in bin, I want to check the header to check the format (jpg, png, etc)
I don't want to use temp files! I have a solution using TEMP FILES.
Solution 1:
I can see that most of you didn't understand the question :) (question was how to validate binary data in buffer, not a file on disk).
I had same problem, and resolved it with:
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->buffer($rawImage);
Solution 2:
The bits start with:
$JPEG = "\xFF\xD8\xFF"
$GIF = "GIF"
$PNG = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"
$BMP = "BM"
$PSD = "8BPS"
$SWF = "FWS"
The other ones I wouldn't know right now, but the big 3 (jpeg,gif,png) usually cover 99%. So, compare the first bytes to those string, and you have your answer.
Solution 3:
Here's an implementation of the function as described by Wrikken
function getImgType($filename) {
$handle = @fopen($filename, 'r');
if (!$handle)
throw new Exception('File Open Error');
$types = array('jpeg' => "\xFF\xD8\xFF", 'gif' => 'GIF', 'png' => "\x89\x50\x4e\x47\x0d\x0a", 'bmp' => 'BM', 'psd' => '8BPS', 'swf' => 'FWS');
$bytes = fgets($handle, 8);
$found = 'other';
foreach ($types as $type => $header) {
if (strpos($bytes, $header) === 0) {
$found = $type;
break;
}
}
fclose($handle);
return $found;
}
Solution 4:
Are the files being uploaded or are they already on the file system?
Try using mime_content_type()
to get the file's MIME format.