1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ImageMimeTypeGuesser\Detectors; |
4
|
|
|
|
5
|
|
|
use \ImageMimeTypeGuesser\Detectors\AbstractDetector; |
6
|
|
|
|
7
|
|
|
class SniffFirstFourBytes extends AbstractDetector |
8
|
|
|
{ |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Try to detect mime type by sniffing the first four bytes. |
12
|
|
|
* |
13
|
|
|
* Credits: Based on the code here: http://phil.lavin.me.uk/2011/12/php-accurately-detecting-the-type-of-a-file/ |
14
|
|
|
* |
15
|
|
|
* Returns: |
16
|
|
|
* - mime type (string) (if it is in fact an image, and type could be determined) |
17
|
|
|
* - false (if it is not an image type that the server knowns about) |
18
|
|
|
* - null (if nothing can be determined) |
19
|
|
|
* |
20
|
|
|
* @param string $filePath The path to the file |
21
|
|
|
* @return string|false|null mimetype (if it is an image, and type could be determined), |
22
|
|
|
* false (if it is not an image type that the server knowns about) |
23
|
|
|
* or null (if nothing can be determined) |
24
|
|
|
*/ |
25
|
|
|
protected function doDetect($filePath) |
26
|
|
|
{ |
27
|
|
|
// PNG, GIF, JFIF JPEG, EXIF JPEF (respectively) |
28
|
|
|
$known = [ |
29
|
|
|
'89504E47' => 'image/png', |
30
|
|
|
'47494638' => 'image/gif', |
31
|
|
|
'FFD8FFE0' => 'image/jpeg', // JFIF JPEG |
32
|
|
|
'FFD8FFE1' => 'image/jpeg', // EXIF JPEG |
33
|
|
|
]; |
34
|
|
|
|
35
|
|
|
$handle = @fopen($filePath, 'r'); |
36
|
|
|
if ($handle === false) { |
37
|
|
|
return; |
38
|
|
|
} |
39
|
|
|
$firstFour = @fread($handle, 4); |
40
|
|
|
if ($firstFour === false) { |
41
|
|
|
return; |
42
|
|
|
} |
43
|
|
|
$key = strtoupper(bin2hex($firstFour)); |
44
|
|
|
if (isset($known[$key])) { |
45
|
|
|
return $known[$key]; |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|