1: <?php
2:
3: 4: 5: 6: 7:
8:
9:
10:
11: 12: 13: 14: 15: 16:
17: class NMimeTypeDetector
18: {
19:
20: 21: 22:
23: final public function __construct()
24: {
25: throw new NStaticClassException;
26: }
27:
28:
29: 30: 31: 32: 33:
34: public static function fromFile($file)
35: {
36: if (!is_file($file)) {
37: throw new FileNotFoundException("File '$file' not found.");
38: }
39:
40: $info = @getimagesize($file);
41: if (isset($info['mime'])) {
42: return $info['mime'];
43:
44: } elseif (extension_loaded('fileinfo')) {
45: $type = preg_replace('#[\s;].*\z#', '', finfo_file(finfo_open(FILEINFO_MIME), $file));
46:
47: } elseif (function_exists('mime_content_type')) {
48: $type = mime_content_type($file);
49: }
50:
51: return isset($type) && preg_match('#^\S+/\S+\z#', $type) ? $type : 'application/octet-stream';
52: }
53:
54:
55: 56: 57: 58: 59:
60: public static function fromString($data)
61: {
62: if (extension_loaded('fileinfo') && preg_match('#^(\S+/[^\s;]+)#', finfo_buffer(finfo_open(FILEINFO_MIME), $data), $m)) {
63: return $m[1];
64:
65: } elseif (strncmp($data, "\xff\xd8", 2) === 0) {
66: return 'image/jpeg';
67:
68: } elseif (strncmp($data, "\x89PNG", 4) === 0) {
69: return 'image/png';
70:
71: } elseif (strncmp($data, "GIF", 3) === 0) {
72: return 'image/gif';
73:
74: } else {
75: return 'application/octet-stream';
76: }
77: }
78:
79: }
80: