ylsunyuan技术论坛中心

 找回密码
 注册(请使用中文注册)
搜索
热搜: 活动 交友 discuz
查看: 907|回复: 0
打印 上一主题 下一主题

非常经典的 PHP 文件上传类

[复制链接]

124

主题

127

帖子

619

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
619
跳转到指定楼层
楼主
发表于 2016-6-7 14:12:42 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
Html代码
  1. <form action="upload.php" method="post" enctype="multipart/form-data" >
  2.     name: <input type="text" name="username" value="" /><br>
  3.     <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
  4.     up pic: <input type="file" name="pic[]" value=""><br>
  5.     up pic: <input type="file" name="pic[]" value=""><br>
  6.     up pic: <input type="file" name="pic[]" value=""><br>
  7.     up pic: <input type="file" name="pic[]" value=""><br>
  8.    
  9.     <input type="submit" value="upload" /><br>
  10.    
  11. </form>
复制代码


核心代码

  1. <?php
  2.   /**  
  3.     file: fileupload.class.php 文件上传类FileUpload
  4.     本类的实例对象用于处理上传文件,可以上传一个文件,也可同时处理多个文件上传
  5.   */
  6.   class FileUpload {  
  7.     private $path = "./uploads";          //上传文件保存的路径
  8.     private $allowtype = array('jpg','gif','png'); //设置限制上传文件的类型
  9.     private $maxsize = 1000000;           //限制文件上传大小(字节)
  10.     private $israndname = true;           //设置是否随机重命名文件, false不随机
  11.    
  12.     private $originName;              //源文件名
  13.     private $tmpFileName;              //临时文件名
  14.     private $fileType;               //文件类型(文件后缀)
  15.     private $fileSize;               //文件大小
  16.     private $newFileName;              //新文件名
  17.     private $errorNum = 0;             //错误号
  18.     private $errorMess="";             //错误报告消息
  19.    
  20.     /**
  21.      * 用于设置成员属性($path, $allowtype,$maxsize, $israndname)
  22.      * 可以通过连贯操作一次设置多个属性值
  23.      *@param  string $key  成员属性名(不区分大小写)
  24.      *@param  mixed  $val  为成员属性设置的值
  25.      *@return  object     返回自己对象$this,可以用于连贯操作
  26.      */
  27.     function set($key, $val){
  28.       $key = strtolower($key);  
  29.       if( array_key_exists( $key, get_class_vars(get_class($this) ) ) ){
  30.         $this->setOption($key, $val);
  31.       }
  32.       return $this;
  33.     }
  34.    
  35.     /**
  36.      * 调用该方法上传文件
  37.      * @param  string $fileFile  上传文件的表单名称  
  38.      * @return bool        如果上传成功返回数true  
  39.      */
  40.    
  41.     function upload($fileField) {
  42.       $return = true;
  43.       /* 检查文件路径是滞合法 */
  44.       if( !$this->checkFilePath() ) {        
  45.         $this->errorMess = $this->getError();
  46.         return false;
  47.       }
  48.       /* 将文件上传的信息取出赋给变量 */
  49.       $name = $_FILES[$fileField]['name'];
  50.       $tmp_name = $_FILES[$fileField]['tmp_name'];
  51.       $size = $_FILES[$fileField]['size'];
  52.       $error = $_FILES[$fileField]['error'];
  53.    
  54.       /* 如果是多个文件上传则$file["name"]会是一个数组 */
  55.       if(is_Array($name)){     
  56.         $errors=array();
  57.         /*多个文件上传则循环处理 , 这个循环只有检查上传文件的作用,并没有真正上传 */
  58.         for($i = 0; $i < count($name); $i++){  
  59.           /*设置文件信息 */
  60.           if($this->setFiles($name[$i],$tmp_name[$i],$size[$i],$error[$i] )) {
  61.             if(!$this->checkFileSize() || !$this->checkFileType()){
  62.               $errors[] = $this->getError();
  63.               $return=false;  
  64.             }
  65.           }else{
  66.             $errors[] = $this->getError();
  67.             $return=false;
  68.           }
  69.           /* 如果有问题,则重新初使化属性 */
  70.           if(!$return)           
  71.             $this->setFiles();
  72.         }
  73.    
  74.         if($return){
  75.           /* 存放所有上传后文件名的变量数组 */
  76.           $fileNames = array();      
  77.           /* 如果上传的多个文件都是合法的,则通过销魂循环向服务器上传文件 */
  78.           for($i = 0; $i < count($name); $i++){  
  79.             if($this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i] )) {
  80.               $this->setNewFileName();  
  81.               if(!$this->copyFile()){
  82.                 $errors[] = $this->getError();
  83.                 $return = false;
  84.               }
  85.               $fileNames[] = $this->newFileName;   
  86.             }           
  87.           }
  88.           $this->newFileName = $fileNames;
  89.         }
  90.         $this->errorMess = $errors;
  91.         return $return;
  92.       /*上传单个文件处理方法*/
  93.       } else {
  94.         /* 设置文件信息 */
  95.         if($this->setFiles($name,$tmp_name,$size,$error)) {
  96.           /* 上传之前先检查一下大小和类型 */
  97.           if($this->checkFileSize() && $this->checkFileType()){  
  98.             /* 为上传文件设置新文件名 */
  99.             $this->setNewFileName();  
  100.             /* 上传文件  返回0为成功, 小于0都为错误 */
  101.             if($this->copyFile()){  
  102.               return true;
  103.             }else{
  104.               $return=false;
  105.             }
  106.           }else{
  107.             $return=false;
  108.           }
  109.         } else {
  110.           $return=false;  
  111.         }
  112.         //如果$return为false, 则出错,将错误信息保存在属性errorMess中
  113.         if(!$return)
  114.           $this->errorMess=$this->getError();   
  115.    
  116.         return $return;
  117.       }
  118.     }
  119.    
  120.     /**  
  121.      * 获取上传后的文件名称
  122.      * @param  void   没有参数
  123.      * @return string 上传后,新文件的名称, 如果是多文件上传返回数组
  124.      */
  125.     public function getFileName(){
  126.       return $this->newFileName;
  127.     }
  128.    
  129.     /**
  130.      * 上传失败后,调用该方法则返回,上传出错信息
  131.      * @param  void   没有参数
  132.      * @return string  返回上传文件出错的信息报告,如果是多文件上传返回数组
  133.      */
  134.     public function getErrorMsg(){
  135.       return $this->errorMess;
  136.     }
  137.    
  138.     /* 设置上传出错信息 */
  139.     private function getError() {
  140.       $str = "上传文件<font color='red'>{$this->originName}</font>时出错 : ";
  141.       switch ($this->errorNum) {
  142.         case 4: $str .= "没有文件被上传"; break;
  143.         case 3: $str .= "文件只有部分被上传"; break;
  144.         case 2: $str .= "上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值"; break;
  145.         case 1: $str .= "上传的文件超过了php.ini中upload_max_filesize选项限制的值"; break;
  146.         case -1: $str .= "未允许类型"; break;
  147.         case -2: $str .= "文件过大,上传的文件不能超过{$this->maxsize}个字节"; break;
  148.         case -3: $str .= "上传失败"; break;
  149.         case -4: $str .= "建立存放上传文件目录失败,请重新指定上传目录"; break;
  150.         case -5: $str .= "必须指定上传文件的路径"; break;
  151.         default: $str .= "未知错误";
  152.       }
  153.       return $str.'<br>';
  154.     }
  155.    
  156.     /* 设置和$_FILES有关的内容 */
  157.     private function setFiles($name="", $tmp_name="", $size=0, $error=0) {
  158.       $this->setOption('errorNum', $error);
  159.       if($error)
  160.         return false;
  161.       $this->setOption('originName', $name);
  162.       $this->setOption('tmpFileName',$tmp_name);
  163.       $aryStr = explode(".", $name);
  164.       $this->setOption('fileType', strtolower($aryStr[count($aryStr)-1]));
  165.       $this->setOption('fileSize', $size);
  166.       return true;
  167.     }
  168.    
  169.     /* 为单个成员属性设置值 */
  170.     private function setOption($key, $val) {
  171.       $this->$key = $val;
  172.     }
  173.    
  174.     /* 设置上传后的文件名称 */
  175.     private function setNewFileName() {
  176.       if ($this->israndname) {
  177.         $this->setOption('newFileName', $this->proRandName());   
  178.       } else{  
  179.         $this->setOption('newFileName', $this->originName);
  180.       }  
  181.     }
  182.    
  183.     /* 检查上传的文件是否是合法的类型 */
  184.     private function checkFileType() {
  185.       if (in_array(strtolower($this->fileType), $this->allowtype)) {
  186.         return true;
  187.       }else {
  188.         $this->setOption('errorNum', -1);
  189.         return false;
  190.       }
  191.     }
  192.    
  193.     /* 检查上传的文件是否是允许的大小 */
  194.     private function checkFileSize() {
  195.       if ($this->fileSize > $this->maxsize) {
  196.         $this->setOption('errorNum', -2);
  197.         return false;
  198.       }else{
  199.         return true;
  200.       }
  201.     }
  202.    
  203.     /* 检查是否有存放上传文件的目录 */
  204.     private function checkFilePath() {
  205.       if(empty($this->path)){
  206.         $this->setOption('errorNum', -5);
  207.         return false;
  208.       }
  209.       if (!file_exists($this->path) || !is_writable($this->path)) {
  210.         if (!@mkdir($this->path, 0755)) {
  211.           $this->setOption('errorNum', -4);
  212.           return false;
  213.         }
  214.       }
  215.       return true;
  216.     }
  217.    
  218.     /* 设置随机文件名 */
  219.     private function proRandName() {     
  220.       $fileName = date('YmdHis')."_".rand(100,999);     
  221.       return $fileName.'.'.$this->fileType;  
  222.     }
  223.    
  224.     /* 复制上传文件到指定的位置 */
  225.     private function copyFile() {
  226.       if(!$this->errorNum) {
  227.         $path = rtrim($this->path, '/').'/';
  228.         $path .= $this->newFileName;
  229.         if (@move_uploaded_file($this->tmpFileName, $path)) {
  230.           return true;
  231.         }else{
  232.           $this->setOption('errorNum', -3);
  233.           return false;
  234.         }
  235.       } else {
  236.         return false;
  237.       }
  238.     }
  239.   }
复制代码



Demo
  1. <?php
  2.     //包含一个文件上传类中的上传类
  3.     include "fileupload.class.php";
  4.    
  5.     $up = new fileupload;
  6.     //设置属性(上传的位置, 大小, 类型, 名是是否要随机生成)
  7.     $up -> set("path", "./images/");
  8.     $up -> set("maxsize", 2000000);
  9.     $up -> set("allowtype", array("gif", "png", "jpg","jpeg"));
  10.     $up -> set("israndname", false);
  11.    
  12.     //使用对象中的upload方法, 就可以上传文件, 方法需要传一个上传表单的名子 pic, 如果成功返回true, 失败返回false
  13.     if($up -> upload("pic")) {
  14.         echo '<pre>';
  15.         //获取上传后文件名子
  16.         var_dump($up->getFileName());
  17.         echo '</pre>';
  18.    
  19.     } else {
  20.         echo '<pre>';
  21.         //获取上传失败以后的错误提示
  22.         var_dump($up->getErrorMsg());
  23.         echo '</pre>';
  24.     }
  25. ?>
复制代码





回复

使用道具 举报

本版积分规则

QQ|Archiver|手机版|小黑屋|ylsunyuan技术论坛 ( 桂ICP备14005218号-1

GMT+8, 2024-4-26 15:52 , Processed in 0.060021 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表