Created
January 30, 2015 04:12
-
-
Save k1ic/ad805d5e3ee9931bea2c to your computer and use it in GitHub Desktop.
获取文件类型(通过读取文件前两个字节判断文件类型)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 获取文件类型(通过读取文件前两个字节判断文件类型) | |
* @param string $path 文件绝对路径 | |
* @return string 文件扩展名 | |
*/ | |
public static function get_file_type ( $path = '' ) { | |
$res = ''; | |
if ( file_exists($path) && is_readable($path) ) { | |
$fh = fopen($path, 'rb'); | |
$bin = fread($fh, 2); //只读前两个字节 | |
fclose($fh); | |
$str_info = unpack('C2chars', $bin); //"C2chars"中的“C”表示将给定二进制字符串解包为无符号字节型 | |
$type_code = intval($str_info['chars1'] . $str_info['chars2']); | |
switch ( $type_code ) { | |
case 3533: | |
$res = 'amr'; | |
break; | |
case 6677: | |
$res = 'bmp'; | |
break; | |
case 7790: | |
$res = 'exe'; | |
break; | |
break; | |
case 7173: | |
$res = 'gif'; | |
break; | |
case 255216: | |
$res = 'jpg'; | |
break; | |
case 7368: | |
$res = 'mp3'; | |
break; | |
case 6063: | |
$res = 'php'; | |
break; | |
case 13780: | |
$res = 'png'; | |
break; | |
case 8297: | |
$res = 'rar'; | |
break; | |
case 4950: | |
$res = 'txt'; | |
break; | |
case 8075: | |
$res = 'zip'; | |
break; | |
default: | |
$res = 'unknown' . $type_code; | |
} | |
} else { | |
$res = !file_exists($path) ? 'file not exists' : ( !is_readable($path) ? 'not a readable file' : '' ); | |
} | |
return $res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment