封装php文件信息管理

原创2019-03-02 15:35:5093
摘要:/**  * @param $fileInfo  文件信息  * @param string $uploadPath 文件到的目录  * @param bool $imageFlag   是否检查图片  * @
/**
 * @param $fileInfo  文件信息
 * @param string $uploadPath 文件到的目录
 * @param bool $imageFlag   是否检查图片
 * @param array $allowExt  规定的文件类型
 * @param int $maxSize  最大大小设置
 */
function upload_file($fileInfo,$uploadPath = './upload',$imageFlag = true , $allowExt = ['jpg', 'png', 'jpeg', 'gif', 'txt'], $maxSize = 2097152){
  //判断文件是否有错误,error  等于0  表示没有错误
    if($fileInfo['error'] == 0){
      //截取上传文件的后缀
        $ext = strtolower(pathinfo($fileInfo['name'],PATHINFO_EXTENSION));
        //判断上传的文件是否符合类型
        if(!in_array($ext,$allowExt)){
            return "文件类型不符";
        }
        //判断上传的大小是否符合
        if($maxSize - $fileInfo['size'] < 0){
            return "文件大小超出";
        }
        //判断是否有upload目录
        if(!is_dir($uploadPath)){
            mkdir($uploadPath,0777,true);
        }
        //生成随机文件名  uniqid生成一个唯一id  microtime 返回当前 Unix 时间戳和微秒数
        $uniName = md5(uniqid(microtime(true),true));
        $dest = $uploadPath.DIRECTORY_SEPARATOR.$uniName.'.'.$ext;
        echo $dest;
        //移动文件   只有上传的文件才能用该函数
        if(move_uploaded_file($fileInfo['tmp_name'],$dest)){
            return '文件上传成功!';
        }
        return '文件上传失败!';
    }else{
        $res = '';
        switch($fileInfo['error']){
            case 1:
                $res = '超过了php配置文件中upload_max_filesize选项中的值';
                break;
            case 2:
                $res = '超过了表单max_file_size选项的值';
                break;
            case 3:
                $res = '文件部分被上传';
                break;
            case 4:
                $res = '没有选择上传文件';
                break;
            case 6:
            case 7:
                $res = '系统错误';
                break;
        }
        return $res;
    }
}


批改老师:天蓬老师批改时间:2019-03-02 15:41:26
老师总结:这个封装,功能很完整呢, 特别是对上传错误的判断,非常齐全

发布手记

热门词条