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

yipeiwu_com5年前PHP代码库

本文实例讲述了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程序设计有所帮助。

相关文章

PHP的explode和implode的使用说明

说到php,函数便长短常主要的,也是php爱好者,和喜好php进阶的朋友们必须控制的东东,学习php的友朋们也晓得,数组也是必需把握的,能够那样道,进阶php,也便是学习php中的数组而...

用PHP写的基于Memcache的Queue实现代码

php类代码: 复制代码 代码如下: <?php class MQ{ public static $client; private static $m_real; private...

PHP序列化的四种实现方法与横向对比

PHP序列化的四种实现方法与横向对比

一、PHP 序列化变量的 4 种方法 序列化是将变量转换为可保存或传输的字符串的过程;反序列化就是在适当的时候把这个字符串再转化成原来的变量使用。这两个过程结合起来,可以轻松地存储和传输...

php实现构建排除当前元素的乘积数组方法

构建乘积数组 给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*.....

php中支持多种编码的中文字符串截取函数!

支持多种编码的中文字符串截取函数!   复制代码 代码如下:/*     * @todo 中文截取,支持g...