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