通过字节识别文件
http://blog.sina.com.cn/s/blog_62b832910100vmbq.html
通过相关文件格式,获取文件实际类型
YII的代码
01 | class FileTools{ |
02 | public static function getFileType( $file ,& $fileType ,& $mime ){ |
03 | $bin = substr ( $file ,0,2); |
04 | $strInfo = @unpack( "C2chars" , $bin ); |
05 | $typeCode = intval ( $strInfo [ 'chars1' ]. $strInfo [ 'chars2' ]); |
06 | $fileType = '' ; |
07 | switch ( $typeCode ) |
08 | { |
09 | case 7790: |
10 | $fileType = 'exe' ; |
11 | return false; |
12 | break ; |
13 | case 7784: |
14 | $fileType = 'midi' ; |
15 | return false; |
16 | break ; |
17 | case 8297: |
18 | $fileType = 'rar' ; |
19 | return false; |
20 | break ; |
21 | case 255216: |
22 | $fileType = 'jpg' ; |
23 | $mime = 'image/jpeg' ; |
24 | return true; |
25 | break ; |
26 | case 7173: |
27 | $fileType = 'gif' ; |
28 | $mime = 'image/gif' ; |
29 | return true; |
30 | break ; |
31 | case 6677: |
32 | $fileType = 'bmp' ; |
33 | $mime = 'image/bmp' ; |
34 | return true; |
35 | break ; |
36 | case 13780: |
37 | $fileType = 'png' ; |
38 | $mime = 'image/png' ; |
39 | return true; |
40 | break ; |
41 | default : |
42 | return false; |
43 | break ; |
44 | } |
45 | return false; |
46 | } |
47 | public static function getMimeType( $file , $magicFile =null, $checkExtension =true) |
48 | { |
49 | if (function_exists( 'finfo_open' )) |
50 | { |
51 | $options =defined( 'FILEINFO_MIME_TYPE' ) ? FILEINFO_MIME_TYPE : FILEINFO_MIME; |
52 | $info = $magicFile ===null ? finfo_open( $options ) : finfo_open( $options , $magicFile ); |
53 |
54 | if ( $info && ( $result =finfo_file( $info , $file ))!==false) |
55 | return $result ; |
56 | } |
57 |
58 | if (function_exists( 'mime_content_type' ) && ( $result =mime_content_type( $file ))!==false) |
59 | return $result ; |
60 | return $checkExtension ? self::getMimeTypeByExtension( $file ) : null; |
61 | } |
62 | /** |
63 | * Determines the MIME type based on the extension name of the specified file. |
64 | * This method will use a local map between extension name and MIME type. |
65 | * @param string $file the file name. |
66 | * @param string $magicFile the path of the file that contains all available MIME type information. |
67 | * If this is not set, the default 'system.utils.mimeTypes' file will be used. |
68 | * This parameter has been available since version 1.1.3. |
69 | * @return string the MIME type. Null is returned if the MIME type cannot be determined. |
70 | */ |
71 | public static function getMimeTypeByExtension( $file , $magicFile =null) |
72 | { |
73 | static $extensions ; |
74 | if ( $extensions ===null) |
75 | $extensions = $magicFile ===null ? require ( 'mimeTypes.php' ) : $magicFile ; |
76 | if (( $ext = pathinfo ( $file , PATHINFO_EXTENSION))!== '' ) |
77 | { |
78 | $ext = strtolower ( $ext ); |
79 | if (isset( $extensions [ $ext ])) |
80 | return $extensions [ $ext ]; |
81 | } |
82 | return null; |
83 | } |
84 | } |