PHP实现单文件、多文件上传 封装 面向对象实现文件上传

文件上传配置

客户端配置

1、表单页面

2、表单的发送方式为post

3、添加enctype = "multipart/form-data"

<form action="doAction.php" method="post" enctype="multipart/form-data">
    请上传文件<input type="file" name="myFile" /></br>
    <input type="submit" value="上传文件" />
</form>

$_FILES中保存着上传文件的信息

name:上传文件的名称

type:上传文件的MIME类型

tmp_name:上传到服务器上的临时文件名

size:上传文件的大小

error:上传文件错误号

有两种方式:move_uploaded_file  或  copy

    //$_FILES 文件上传变量
    print_r($_FILES);
    
    //获取我们需要的内容
    $filename=$_FILES['myFile']['name'];
    $type=$_FILES['myFile']['type'];
    $tmp_name=$_FILES['myFile']['tmp_name'];
    $error=$_FILES['myFile']['error'];
    $size=$_FILES['myFile']['size'];
    
    //将服务器上的临时文件移动到指定目录下
    //move_uploaded_file($tmp_name,$destination)
    //$tmp_name 临时文件  $destination 指定目录下  后面跟文件名
    move_uploaded_file($tmp_name, "images/".$filename);
    
    //copy($src,$dst) 将文件拷贝到指定目录 拷贝成功返回true 否则返回false
    //copy($tmp_name,"images/".$filename);

文件上传配置

PHP   php.ini 里面

服务器端配置:

uploads:

file_uploads = On  支持HTTP上传

upload_tmp_dir  临时文件保存的目录

upload_max_filesize  允许上传文件的最大值

max_file_uploads  允许一次上传的最大文件数

post_max_size  POST方式发送数据最大值

错误信息说明:

UPLOAD_ERR_OK : 值为0,没有错误发生,文件上传成功

UPLOAD_ERR_INI_SIZE: 值为1,上传的文件超过了php.ini中 upload_max_filesize选项限制的值

UPLOAD_ERR_FORM_SIZE: 值为2,上传文件的大小超过了HTML表单中 MAX_FILE_SIZE选项指定的值。

UPLOAD_ERR_PARTIAL: 值为3,文件只有部分被上传。

单文件上传

<?php 
    //$_FILES 文件上传变量
    print_r($_FILES);
    
    //获取我们需要的内容
    $fileInfo=$_FILES['myFile'];
    $maxSize = 2097152; //允许的最大值
    $allowExt = array('jpeg','jpg','png','gif','wbmp');
    $flag=true; //检测是否为真实图片类型
   
    //1、判断错误号
    if ($fileInfo['error'] == 0){
        //判断上传文件的大小
        if($fileInfo['size']>$maxSize){
            exit('上传文件过大');
        }
        //in_array() 函数搜索数组中是否存在指定的值。判断下上传的类型是不是在允许的范围内
        //$ext 上传文件扩展名
        //$allowExt 允许上传文件类型
        //取扩展名 $ext = strtolower(end(explode('.',$fileInfo['name'])))
        //或者 $ext = pathinfo($fileInfo['name'],PATHINFO_EXTENSION);
        $ext = pathinfo($fileInfo['name'],PATHINFO_EXTENSION);
        if(!in_array($ext, $allowExt)){
            exit('非法文件类型');
        }
        //判断文件是否是通过HTTP POST方式上传来的
        //is_uploaded_file()函数判断指定的文件是否是通过 HTTP POST 上传的。
        if (!is_uploaded_file($fileInfo['tmp_name'])){
            exit('文件不是通过HTTP POST方式上传上来的');
        }
        //检测是否为真实的图片类型
        //getimagesize($filename) 得到指定图片信息,如果是图片返回数组
        if($flag){
            if (!getimagesize($fileInfo['tmp_name'])){
                exit('不是真正的图片类型');
            }
        }
        
        $path = 'images'; //临时目录
        //如果目录不存在
        //file_exists() 函数检查文件或目录是否存在。
        //mkdir() 函数创建目录。
        //chmod() 函数改变文件模式。
        if(!file_exists($path)){
            mkdir($path,0777,true);
            chmod($path, 0777);
        }
        //确保文件名唯一,防止重名产生覆盖
        $uniName=md5(uniqid(microtime(true),true)).'.'.$ext;
        $destination=$path.'/'.$uniName;
        if (move_uploaded_file($fileInfo['tmp_name'], $destination)){
            echo '文件上传成功';
        }else {
            echo '文件上传失败';
        }
    }else{
        switch ($fileInfo['error']){
            case 1:
                echo '上传文件超过了PHP配置文件中upload_max_filesize选项的值';
                break;
            case 2:
                echo '超过了表单MAX_FILE_SIZE限制的大小';
                break;
            case 3:
                echo '文件部分被上传';
                break;
            case 4:
                echo '没有选择上传文件';
                break;
            case 6:
                echo '没有找到临时目录';
                break;
            case 7:
            case 8:
                echo '系统错误';
                break;
        }
    }
    
?>

单文件上传封装

封装文件upload.func.php:

<?php 
//$fileInfo = $_FILES['myFile'];

function uploadFile($fileInfo,$allowExt=array('jpeg','jpg','gif','png'),$path = 'images',$flag = true,$maxSize = 2097152){
    //判断错误号
    if ($fileInfo['error']>0){
        switch ($fileInfo['error']){
            case 1:
                $mes = '上传文件超过了PHP配置文件中upload_max_filesize选项的值';
                break;
            case 2:
                $mes = '超过了表单MAX_FILE_SIZE限制的大小';
                break;
            case 3:
                $mes = '文件部分被上传';
                break;
            case 4:
                $mes = '没有选择上传文件';
                break;
            case 6:
                $mes = '没有找到临时目录';
                break;
            case 7:
            case 8:
                $mes = '系统错误';
                break;
        }
        echo ( $mes );
        return false;
    }
    
    //判断文件类型
    //$allowExt = array('jpeg','jpg','png','gif','wbmp');
    $ext = pathinfo ( $fileInfo ['name'], PATHINFO_EXTENSION );
        //is_array() 函数用于检测变量是否是一个数组。
    if (!is_array($allowExt)){
        exit('系统错误,请使用数组的方式');
    }
    if (! in_array ( $ext, $allowExt )) {
        exit ( '非法文件类型' );
    }
    
    //判断文件大小
    //$maxSize = 2097152; //2M
    if ($fileInfo['size']>$maxSize){
        exit('上传文件过大');
    }
    
    //判断文件是否是真实图片
    //$flag = true;
    //var_dump(getimagesize($fileInfo['tmp_name']));
    
    if($flag){
        if(!getimagesize($fileInfo['tmp_name'])){
            exit('不是真实图片类型');
        }
    }
    
    //判断是否是HTTP POST请求方式上传
    if (!is_uploaded_file($fileInfo['tmp_name'])){
        exit('文件不是通过HTTP POST方式上传上来的');
    }
    
    //判断临时目录,创建目录
    //$path = 'images';
        //如果目录不存在
        //file_exists() 函数检查文件或目录是否存在。
        //mkdir() 函数创建目录。
        //chmod() 函数改变文件模式。
    if (!file_exists($path)){
        mkdir($path,0777,true);
        chmod($path,0777);
    }
    
    //确保文件名唯一,防止重名产生覆盖
    $uniName = md5(uniqid(microtime(true),true)).'.'.$ext;
    $destination = $path.'/'.$uniName;  //指定目录下
    
    //判断是否上传成功
    if (!@move_uploaded_file($fileInfo['tmp_name'], $destination)){
        exit('文件上传失败');
    }
    
    //echo '文件上传成功';
    //     return array(
    //         'newName'=>$destination,
    //         'size'=>$fileInfo['size'],
    //         'type'=>$fileInfo['type']
    //     );
    return $destination;
}
?>

处理文件:doActionfunc.php

<?php 
    header('content-type:text/html;charset=utf-8');
    include_once ('upload.func.php');
    $fileInfo = $_FILES['myFile'];
    print_r($fileInfo);
    
//     $newName = uploadFile($fileInfo);
//     echo $newName;
    // $newName=uploadFile($fileInfo,'imooc');
    // echo $newName;
    //$allowExt='txt';
    $allowExt=array('jpeg','jpg','png','gif','html','txt','css');
    $newName=uploadFile($fileInfo,$allowExt,'img',true);
    echo $newName;
?>

HTML页面

<!DOCTYPE>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>上传</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="default.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form action="doActionfunc.php" method="post" enctype="multipart/form-data">
        请选择您要上传的文件:<input type="file" name='myFile' />
        <input type="submit" value="上传文件" />
    </form>
</body>
</html>

多个单文件上传

<!-- 多文件 单文件 上传封装函数 -->
<?php 
    
    /**
     * 构建上传文件信息
     * @return unknown
     * 判断是多个文件还是单个文件
     */

    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]['type'] = $file['type'][$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',$flag=true,$maxSize=1048576,$allowExt=array('jpeg','jpg','png','gif')){
        
        //判断错误号
        if($fileInfo['error']===UPLOAD_ERR_OK){
            //检测上传得到小
            if($fileInfo['size']>$maxSize){
                $res['mes']=$fileInfo['name'].'上传文件过大';
            }
            $ext=getExt($fileInfo['name']);
            //检测上传文件的文件类型
            if(!in_array($ext,$allowExt)){
                $res['mes']=$fileInfo['name'].'非法文件类型';
            }
            //检测是否是真实的图片类型
            if($flag&&in_array($ext,$allowExt)){
                if(!getimagesize($fileInfo['tmp_name'])){
                    $res['mes']=$fileInfo['name'].'不是真实图片类型';
                }
            }
            //检测文件是否是通过HTTP POST上传上来的
            if(!is_uploaded_file($fileInfo['tmp_name'])){
                $res['mes']=$fileInfo['name'].'文件不是通过HTTP POST方式上传上来的';
            }
            if(!empty($res)){return $res;}
            //$path='./uploads';
            if(!file_exists($path)){
                mkdir($path,0777,true);
                chmod($path,0777);
            }
            $uniName=getUniName();
            $destination=$path.'/'.$uniName.'.'.$ext;
            if(!move_uploaded_file($fileInfo['tmp_name'],$destination)){
                $res['mes']=$fileInfo['name'].'文件移动失败';
            }
            $res['mes']=$fileInfo['name'].'上传成功';
            $res['dest']=$destination;
            return $res;
            
        }else{
            //匹配错误信息
            switch ($fileInfo ['error']) {
                case 1 :
                    $res['mes'] = '上传文件超过了PHP配置文件中upload_max_filesize选项的值';
                    break;
                case 2 :
                    $res['mes'] = '超过了表单MAX_FILE_SIZE限制的大小';
                    break;
                case 3 :
                    $res['mes'] = '文件部分被上传';
                    break;
                case 4 :
                    $res['mes'] = '没有选择上传文件';
                    break;
                case 6 :
                    $res['mes'] = '没有找到临时目录';
                    break;
                case 7 :
                case 8 :
                    $res['mes'] = '系统错误';
                    break;
            }
            return $res;
        }
        
    }

?>
<?php 
    header('content-type:text/html;charset=utf-8');
    include_once ('common.func.php');
    include_once ('upload.func1.php');
    $files=getFiles();
    foreach ($files as $fileInfo){
        $res=uploadFile($fileInfo);
        echo $res['mes'],'<br/>';
        $uploadFiles[]=$res['dest'];
    }
    $uploadFiles=array_values(array_filter($uploadFiles));
    print_r($uploadFiles);
?>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>上传</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="default.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form action="doAction1func.php" method="post" enctype="multipart/form-data">
        请选择您要上传的文件:<input type="file" name='myFile1' /><br>
        请选择您要上传的文件:<input type="file" name='myFile[]' /><br>
        请选择您要上传的文件:<input type="file" name='myFile[]' /><br>
        请选择您要上传的文件:<input type="file" name='myFile[]' multiple="multiple" /><br>
        <input type="submit" value="上传文件" />
    </form>
</body>
</html>

 面向对象实现文件上传

<?php 
class upload{
    protected $fileName;
    protected $maxSize;
    protected $allowMime;
    protected $allowExt;
    protected $uploadPath;
    protected $imgFlag;
    protected $fileInfo;
    protected $error;
    protected $ext;
    /**
     * @param string $fileName
     * @param string $uploadPath
     * @param string $imgFlag
     * @param number $maxSize
     * @param array $allowExt
     * @param array $allowMime
     */
    public function __construct($fileName='myFile',$uploadPath='./uploads',$imgFlag=true,$maxSize=5242880,$allowExt=array('jpeg','jpg','png','gif'),$allowMime=array('image/jpeg','image/png','image/gif')){
        $this->fileName=$fileName;
        $this->maxSize=$maxSize;
        $this->allowMime=$allowMime;
        $this->allowExt=$allowExt;
        $this->uploadPath=$uploadPath;
        $this->imgFlag=$imgFlag;
        $this->fileInfo=$_FILES[$this->fileName];
    }
    /**
     * 检测上传文件是否出错
     * @return boolean
     */
    protected function checkError(){
        if(!is_null($this->fileInfo)){
            if($this->fileInfo['error']>0){
                switch($this->fileInfo['error']){
                    case 1:
                        $this->error='超过了PHP配置文件中upload_max_filesize选项的值';
                        break;
                    case 2:
                        $this->error='超过了表单中MAX_FILE_SIZE设置的值';
                        break;
                    case 3:
                        $this->error='文件部分被上传';
                        break;
                    case 4:
                        $this->error='没有选择上传文件';
                        break;
                    case 6:
                        $this->error='没有找到临时目录';
                        break;
                    case 7:
                        $this->error='文件不可写';
                        break;
                    case 8:
                        $this->error='由于PHP的扩展程序中断文件上传';
                        break;
                        
                }
                return false;
            }else{
                return true;
            }
        }else{
            $this->error='文件上传出错';
            return false;
        }
    }
    /**
     * 检测上传文件的大小
     * @return boolean
     */
    protected function checkSize(){
        if($this->fileInfo['size']>$this->maxSize){
            $this->error='上传文件过大';
            return false;
        }
        return true;
    }
    /**
     * 检测扩展名
     * @return boolean
     */
    protected function checkExt(){
        $this->ext=strtolower(pathinfo($this->fileInfo['name'],PATHINFO_EXTENSION));
        if(!in_array($this->ext,$this->allowExt)){
            $this->error='不允许的扩展名';
            return false;
        }
        return true;
    }
    /**
     * 检测文件的类型
     * @return boolean
     */
    protected function checkMime(){
        if(!in_array($this->fileInfo['type'],$this->allowMime)){
            $this->error='不允许的文件类型';
            return false;
        }
        return true;
    }
    /**
     * 检测是否是真实图片
     * @return boolean
     */
    protected function checkTrueImg(){
        if($this->imgFlag){
            if(!@getimagesize($this->fileInfo['tmp_name'])){
                $this->error='不是真实图片';
                return false;
            }
            return true;
        }
    }
    /**
     * 检测是否通过HTTP POST方式上传上来的
     * @return boolean
     */
    protected function checkHTTPPost(){
        if(!is_uploaded_file($this->fileInfo['tmp_name'])){
            $this->error='文件不是通过HTTP POST方式上传上来的';
            return false;
        }
        return true;
    }
    /**
     *显示错误 
     */
    protected function showError(){
        exit('<span style="color:red">'.$this->error.'</span>');
    }
    /**
     * 检测目录不存在则创建
     */
    protected function checkUploadPath(){
        if(!file_exists($this->uploadPath)){
            mkdir($this->uploadPath,0777,true);
        }
    }
    /**
     * 产生唯一字符串
     * @return string
     */
    protected function getUniName(){
        return md5(uniqid(microtime(true),true));
    }
    /**
     * 上传文件
     * @return string
     */
    public function uploadFile(){
        if($this->checkError()&&$this->checkSize()&&$this->checkExt()&&$this->checkMime()&&$this->checkTrueImg()&&$this->checkHTTPPost()){
            $this->checkUploadPath();
            $this->uniName=$this->getUniName();
            $this->destination=$this->uploadPath.'/'.$this->uniName.'.'.$this->ext;
            if(@move_uploaded_file($this->fileInfo['tmp_name'], $this->destination)){
                return  $this->destination;
            }else{
                $this->error='文件移动失败';
                $this->showError();
            }
        }else{
            $this->showError();
        }
    }
}
<?php 
header('content-type:text/html;charset=utf-8');
require_once 'upload.class.php';
$upload=new upload('myFile1','imooc');
$dest=$upload->uploadFile();
echo $dest;
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
    <form action="doAction6.php" method="post" enctype="multipart/form-data">
           请选择您要上传的文件:<input type="file" name='myFile1' />
        <input type="submit" value="上传文件" />
    </form>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/alice-shan/p/9312185.html