php 读取文件头判断文件类型的实现代码

yipeiwu_com7年前PHP代码库
php代码实现读取文件头判断文件类型,支持图片、rar、exe等后缀。
案例:
复制代码 代码如下:

<?php $filename = "11.jpg";
//为图片的路径可以用d:/upload/11.jpg等绝对路径
$file = fopen($filename, "rb");
$bin = fread($file, 2); //只读2字节
fclose($file);
$strInfo = @unpack("C2chars", $bin);
$typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
$fileType = '';
switch ($typeCode) {
case 7790: $fileType = 'exe'; break;
case 7784: $fileType = 'midi'; break;
case 8297: $fileType = 'rar'; break;
case 255216: $fileType = 'jpg'; break;
case 7173: $fileType = 'gif'; break;
case 6677: $fileType = 'bmp'; break;
case 13780: $fileType = 'png'; break;
default: echo'unknown';
}
echo'这是一个'.$fileType.' file:'.$typeCode;

案例:
复制代码 代码如下:

?>
//linux下php还有个函数可以判断文件类型
<?php
echo mime_content_type('11.gif') . "\n";
echo mime_content_type('22.php');
?>

相关文章

关于php fread()使用技巧

说明 string fread ( int handle, int length ) fread() 从文件指针 handle 读取最多 length 个字节。该函数在读取完最多 len...

php获取百度收录、百度热词及百度快照的方法

本文实例讲述了php获取百度收录、百度热词及百度快照的方法。分享给大家供大家参考。具体如下: 获取百度收录: <?php /* 抓取百度收录代码 */ function...

php正则表达式学习笔记

php正则表达式学习笔记

php正则表达式学习笔记分享: 1.创建正则表达式 $regex = '/\d/i'; 与JavaScript中的第一个方式有点像,只是这里的话是个字符串。  2.正则表达式中...

完美解决PHP中文乱码

一.首先是PHP网页的编码 1. php文件本身的编码与网页的编码应匹配 a. 如果欲使用gb2312编码,那么php要输出头:header(“Content-Type: text/ht...

探讨方法的重写(覆载)详解

复制代码 代码如下:<?php class Cart{  public function Cart(){   echo...