当前位置: 移动技术网 > IT编程>开发语言>PHP > php实现不通过扩展名准确判断文件类型的方法【finfo_file方法与二进制流】

php实现不通过扩展名准确判断文件类型的方法【finfo_file方法与二进制流】

2017年12月12日  | 移动技术网IT编程  | 我要评论

奇书网电子书下载txt免费下载,老公pk老婆铃声,穿衣打扮技巧

本文实例讲述了php实现不通过扩展名准确判断文件类型的方法。分享给大家供大家参考,具体如下:

第一种方法

通过php的finfo_file()

$handle=finfo_open(fileinfo_mime_type);//this function opens a magic database and returns its resource. 
$fileinfo=finfo_file($handle,'./test.txt');// return information about a file
finfo_close($handle);
print_r($fileinfo);
echo '==========="\n"';

另外

finfo_buffer: return information about a string buffer
finfo_close: close fileinfo resource
mime_content_type:detect mime content-type for a file (deprecated)

第二种方法

通过二进制流获取文件内容

$fp=fopen('test.txt','r')///实际是image/png
$bin = fread($fp, 2); //只读2字节
fclose($fp);
$str_info = @unpack(“c2chars”, $bin);//unpack data from binary string
$type_code = intval($str_info['chars1'].$str_info['chars2']);// get the integer value of a variable
$file_type = ”;
switch ($type_code) {
case 7790:
$file_type = 'exe';
break;
case 7784:
$file_type = 'midi';
break;
case 8075:
$file_type = 'zip';
break;
case 8297:
$file_type = 'rar';
break;
case 255216:
$file_type = 'jpg';
break;
case 7173:
$file_type = 'gif';
break;
case 6677:
$file_type = 'bmp';
break;
case 13780:
$file_type = 'png';
break;
default:
$file_type = 'unknown';
break;
}

更多关于php相关内容感兴趣的读者可查看本站专题:《php文件操作总结》、《php网络编程技巧总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家php程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网