PHP取二进制文件头快速判断文件类型是否属于zip/rar格式

<?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)
?>

参考文章链接:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦里逆天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值