美文网首页
PHP文件上传封装

PHP文件上传封装

作者: peng_js | 来源:发表于2017-06-30 14:02 被阅读0次

    文件上传封装
    <?php

    include 'uploadone.php';
    header("Content-type: text/html; charset=utf-8");
    //封装获取文件名后缀
    function getExt($fileName){
    return strtolower(pathinfo($fileName,PATHINFO_EXTENSION));
    }
    //获取唯一文件名
    function getUniname(){
    return md5(uniqid(microtime(true),true));
    }
    //处理多文件上传数据
    function getFiles(){

    $i=0;
    foreach ($_FILES as $file){
        if(is_string($file['name'])){
            $files[$i]=$file;
            $i++;
        }elseif (is_array($file['name'])){
            //循环把没一项的值拿出来合并
            foreach ($file['name'] as $key=>$val){
                $files[$i]['name']=$file['name'][$key];
                $files[$i]['tmp_name']=$file['tmp_name'][$key];
                $files[$i]['error']=$file['error'][$key];
                $files[$i]['size']=$file['size'][$key];
                $i++;
            }
    
        }
    
    }
    return $files;
    

    }
    function uploadFile($fileInfo,$path='uploads',$maxSize=1048576,$allowExt=array('jpg','jpeg','png','gif'),$flag=true){
    if($fileInfo['error']===0){
    //获取文件名后缀
    $ext=getExt($fileInfo['name']);
    //检测上传文件大小
    if($fileInfo['size']>$maxSize) $res['msg']=$fileInfo['name'].'上传文件过大';
    //检测允许上传文件的类型
    if(!in_array($ext,$allowExt)) $res['msg']=$fileInfo['name'].'文件上传类型错误!!';
    //检测是否是图片
    //$flag=true;
    if($flag){
    if(@!getimagesize($fileInfo['tmp_name'])){
    //var_dump(getimagesize($fileInfo['tmp_name']));
    $res['msg']=$fileInfo['name'].'不是图片类型';
    }
    }
    //检测文件是否是通过HTTP POST上传的
    //is_uploaded_file — 判断文件是否是通过 HTTP POST 上传的
    if(!is_uploaded_file($fileInfo['tmp_name'])) $res['msg']='文件不是通过HTTP POST上传的';
    if(isset($res)) return $res;
    $uniName=getUniname();
    $path='./uploads';
    if(!file_exists($path)){
    mkdir($path,0777,true);
    chomd($path,0777);
    }
    $destination=$path.'/'.$uniName.'.'.$ext;
    if(!move_uploaded_file($fileInfo['tmp_name'],$destination)){
    $res['msg']=$fileInfo['name'].'文件移动失败';
    }
    $res['msg']=$fileInfo['name'].'文件上传成功';
    $res['dest']=$destination;
    return $res;
    }else{
    switch($fileInfo['error']){
    case 1:
    $res['msg']='上传的文件超过PHP upload_max_fizesize的值';
    break;
    case 2:
    $res['msg']='超过表单MAX_FIZE_SIZE限制大小';
    break;
    case 3:
    $res['msg']= '文件部分被上传';
    break;
    case 4:
    $res['msg']= '没有选择上传文件';
    break;
    case 6:
    $res['msg']= '没有找到临时目录';
    break;
    case 7:
    case 8:
    $res['msg']= '系统错误';
    break;
    }
    return $res;
    }
    }

    相关文章

      网友评论

          本文标题:PHP文件上传封装

          本文链接:https://www.haomeiwen.com/subject/gnobcxtx.html