多张图片上传

    function uploads($pic,$path = './upload',$size=10000000,array $type = array('image/jpeg','image/png','image/gif')){
        //实现单文件上传 (对一个上传文件信息的一维数组进行判断)
        function inner($file,$path,$size,$type){
            //定义一个返回的信息
            $newName = '';
            $info = [];
            //1.判断错误号
            if($file['error'] > 0){
                switch($file['error']){
                    case 1:
                        return '上传文件超过了PHP.INI配置文件中upload_max_filesize选项的值';
                    case 2:
                        return '上传文件超过了HTML表单中设置的 FILE_MAX_SIZE的值';
                    case 3:
                        return '只有部分文件被上传';
                    case 4:
                        return '没有文件上传';
                    case 6:
                        return '找不到临时目录';
                    case 7:
                        return '文件写入失败';
                }
            }
            //2.判断文件大小
            if($file['size'] > $size){
                return '上传文件过大';
            }
            //3.判断文件类型是否合法
            if(!in_array($file['type'],$type)){
                return '上传文件类型不合法';
            }
            //4.判断上传保存的目录是否存在 不存在则创建
            $path = rtrim($path,'/\\').'/';
            if(!file_exists($path)){
                mkdir($path,0777,true);
            }
            //5.为上传的文件重命名
            $suffix = strrchr($file['name'],'.');
            do{
                $newName = md5(uniqid().mt_rand(1,10000).time()).$suffix;
            }while(file_exists($path.$newName));
            //6.移动上传文件
            if(move_uploaded_file($file['tmp_name'],$path.$newName)){
                $info['name'] = $newName;
                $info['path'] = $path;
                $info['pathName'] = $path . $newName;
            }
            //7.返回结果
            return $info;
        }

        //2.循环遍历上传文件的多维数组 将多维数组转换成单一文件上传的一位数组后 调用单文件上传的函数
        $file = array();
        $infos = [];
        foreach($_FILES[$pic]['name'] as $k => $v){
            $file['name'] = $v;
            $file['type'] = $_FILES[$pic]['type'][$k];
            $file['tmp_name'] = $_FILES[$pic]['tmp_name'][$k];
            $file['error'] = $_FILES[$pic]['error'][$k];
            $file['size'] = $_FILES[$pic]['size'][$k];
            //调用文件上传函数
            $infos[] = inner($file,$path,$size,$type);
        }
        return $infos;
    }
posted @ 2022-02-28 12:00  unclesun  阅读(73)  评论(0)    收藏  举报