<?php
/**
* 判断文件格式,若头信息的前2个字节为8075/8297则返回true
* @param $filename
* @return bool
*/
function judgeFileType($filename) {
$filehead = fopen($filename, 'r');
// 读2个字节
$bin = fread($filehead, 2);
fclose($filehead);
$str_info = @unpack("C2chars", $bin);
$type_code = intval($str_info['chars1'].$str_info['chars2']);
echo $type_code;
// zip:8075
// rar:8297
$type = array('8075', '8297');
if(in_array($type_code, $type)) {
return true;
} else {
return false;
}
}
/**
* 根据文件头信息判断文件类型
* @param $filename
* @return bool
* @date 2020/7/17
* @time 14:08
* @author mlnt
*/
function judgeFileType2($filename) {
$filehead = fopen($filename, 'r');
// 读2个字节
$bin = fread($filehead, 2);
fclose($filehead);
$str_info = @unpack("C2chars", $bin);
$type_code = intval($str_info['chars1'].$str_info['chars2']);
echo $type_code;
// zip:8075
// rar:8297
$type = array('8075', '8297');
// 手动修改后缀名,并不会改变头信息,例如,把后缀为.rar的压缩包修改为.zip格式,得到的头信息依然是8297
// 获取文件名后缀
$temp = explode(".", $filename);
$extension = end($temp);
/**
* 存在修改后缀名的情况,但是修改后缀名并不会改变头信息,所以可以加判断
*/
if(($extension == 'zip' && $type_code == '8075') || ($extension == 'rar' && $type_code == '8297')) {
return true;
} else {
return false;
}
if(in_array($type_code, $type)) {
return true;
} else {
return false;
}
}
// test.zip为zip压缩格式的文件
// test.rar为test.zip修改后缀后的压缩文件
var_dump(judgeFileType('php_practices/test.zip')); // 8075bool(true)
var_dump(judgeFileType('php_practices/test.rar')); // 8075bool(true)
var_dump(judgeFileType2('php_practices/test.zip')); // 8075bool(true)
var_dump(judgeFileType2('php_practices/test.rar')); // 8075bool(false)
?>
参考文章链接: