最近写的一个Php上传类,可以读取文件头部判断文件真实类型


/**
 * 读取文件头部判断文件准确类型
 */
class UpLoader{

    private $path;
    private $files;
    private $checkFunction;

    /**
     * @param $allow_type 接受参数为过滤类型,目前有"images"和"zip"两种,可以扩展
     */
     function UpLoader($allow_type){

            $this->path = getenv('SINASRV_CACHE_DIR').'zhuanqu_files/';

            switch($allow_type){
                case 'image':
                    $this->checkFunction = 'checkIfImage';
                break;
                case 'zip':
                    $this->checkFunction = 'checkIfZip';
                break;
            }

     }

    /**
     * 执行上传
     * @param $files 参数为$_FILES数组
     */
     public function doUpload($files){

            $this->files = $files;
            $func = $this->checkFunction;

             if($this->files['files']['name'] != ''  && $this->files['files']['error'] == UPLOAD_ERR_OK) {

                $tmp_name = $this->files["files"]["tmp_name"];

                //检查文件类型
                if( $this->$func($tmp_name) ){
                    $name = md5_file($tmp_name);
                    $name = $name.'___'.$this->files["files"]["name"];
                    if(move_uploaded_file($tmp_name, $this->path.$name)){
                        echo '<script> alert("上传成功!"); </script>';
                    }
                }
             }
     }

     private function checkIfImage($fileName){

        $file     = fopen($fileName, "rb");
        $bin      = fread($file, 2); //只读2字节
        fclose($file);
        $strInfo  = @unpack("C2chars", $bin);
        $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
        $fileType = '';

        if($typeCode == 255216 /*jpg*/ || $typeCode == 7173 /*gif*/ || $typeCode == 13780 /*png*/) {
            return true;
        }else{
            echo '<script> alert("仅允许上传jpg/gif/png格式的图片!"); </script>';
            return false;
        }
     }


     private function checkIfZip($fileName){

        $file     = fopen($fileName, "rb");
        $bin      = fread($file, 2); //只读2字节
        fclose($file);
        $strInfo  = @unpack("C2chars", $bin);
        $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
        $fileType = '';

        if($typeCode == 8075) {
            return true;
        }else{
            echo '<script> alert("仅允许上传zip格式的文件!"); </script>';
            return false;
        }
    }

 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值