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

yipeiwu_com6年前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 删除cookie方法详解

我们先来看下相关cookie的机制。 复制代码 代码如下: bool setcookie ( string name [, string value [, int expire [, s...

php 函数中使用static的说明

复制代码 代码如下: function sendHeader($num, $rtarr = null) { static $sapi = null; if ($sapi === null...

PHP递归统计系统中代码行数

本文实例为大家分享了PHP递归统计系统中代码行数的具体代码,供大家参考,具体内容如下 1、统计代码行数,必然用到的两个关键的知识点:函数递归以及文件读取。 函数递归无非就是在函数的代码中...

php 代码优化之经典示例

我用的方法是按key区分块,然后在将块赋给其他的变量,然后再进行一些操作,这样用到了很多的for和foreach,而且代码量也很大,所以被退回来了。 经过上面的指导,发现真的好简单,现在...

从PHP的源码中深入了解stdClass类

在百度百科中,对于stdClass的定义如下:复制代码 代码如下:stdClass在PHP5才开始被流行。而stdClass也是zend的一个保留类。stdClass是PHP的一个基类,...