search
HomeBackend DevelopmentPHP TutorialVery classic PHP file upload class sharing, _PHP tutorial

A very classic PHP file upload class sharing,

File upload is a common function in project development, but the process of file upload is relatively cumbersome, as long as Wherever files are uploaded, these complex codes need to be written. In order to reduce the difficulty of writing functions in each development and to save development time, we usually encapsulate these repeatedly used pieces of code into a class.

<&#63;php 
/** 
 +----------------------------------------------------------------------------- 
 * 文件上传类 
 +----------------------------------------------------------------------------- 
 * @author Administrator 
 +----------------------------------------------------------------------------- 
 */ 
 class FileUpload{ 
   
  private $filepath;  //保存路径 
  private $allowtype=array('gif','jpg','jpeg','png','txt'); 
  private $maxsize=1000000;  //最大允许上传大小 
  private $israndname=true; //是否随机 
  private $orginame; //原始文件名 
  private $tmpname;  //临时文件名 
  private $newname;  //新文件名 
  private $filetype; //文件类型  
  private $filesize; //文件大小 
  private $errornum=''; //错误号 
  private $errormsg; //错误信息 
/** 
 +------------------------------------------------------------------------------ 
 *构造函数 
 +------------------------------------------------------------------------------ 
 * @param string $savepath  保存路径 
 * @param string $allowtype 允许类型 
 * @param string $maxsize  允许大小 
 * 
 +------------------------------------------------------------------------------ 
 */    
  function __construct($option=array()){ 
     foreach ($option as $key=>$value){ 
        
      if (!in_array($key,get_class_vars(get_class($this)))){ 
        continue; 
       } 
      $this->setOption($key, $value);  
     } 
  } 
  function uploadfile($field) { 
     $return=true; 
    if (!$this->CheckPath()) { 
      $this->errormsg=$this->geterrorNum(); 
      return false; 
    } 
    $name=$_FILES[$field]['name']; 
    $tmpname=$_FILES[$field]['tmp_name']; 
    $filesize=$_FILES[$field]['size']; 
    $error=$_FILES[$field]['error'];  
     if (is_array($name)) { 
      $errors=array(); 
       for ($i=0;$i<count($name);$i++){ 
        if ($this->getFile($name[$i],$tmpname[$i],$filesize[$i],$errors[$i])) { 
          if (!$this->CheckSize() && !$this->CheckType()) { 
            $errors=$this->getErrorNum(); 
            return false; 
            }                                 
        }else{ 
            $errors=$this->getErrorNum(); 
            return false; 
        } 
        if (!$return) { 
          $this->getFile(); 
        } 
       } 
       if ($return) { 
        $fileNames=array(); 
        for ($i=0;$i<count($name);$i++){ 
          if ($this->getFile($name[$i], $tmpname[$i], $filesize[$i], $filesize[$i])) { 
            $this->SetFileName(); 
            if (!$this->MoveFile()) { 
              $errors[]=$this->getErrorNum(); 
              $return=false; 
            }else{ 
              $fileNames[]=$this->getNewName(); 
            } 
          }         
        } 
        $this->newname=$fileNames; 
       } 
        $this->errormsg=$errors; 
        return $return; 
        
     }else{  
      if($this->getFile($name,$tmpname,filesize,$error)){ 
        if(!$this->CheckSize()){ 
          return false; 
        } 
        if(!$this->CheckType()){ 
          return false; 
        } 
         $this->SetFileName(); 
        if ($this->MoveFile()) { 
            return true; 
        }  
      }else{ 
      return false; 
      } 
        
      if (!$return) { 
      $this->setOption('ErrorNum', 0); 
      $this->errormsg=$this->geterrorNum(); 
      } 
     return $return;  
   } 
  } 
  /** 
   +------------------------------------------------------------------------ 
   *设置类属性值函数 
   +------------------------------------------------------------------------ 
   * @param mix $key 
   * @param mix $value 
   */ 
  private function setOption($key,$value){ 
    $key=strtolower($key); 
    $this->$key=$value; 
  } 
  /** 
   +--------------------------------------------------------------------------- 
   * 获取文件变量参数函数 
   +--------------------------------------------------------------------------- 
   * @param string $name 
   * @param string $tmp_name 
   * @param number $size 
   * @param number $error 
   */ 
  private function getFile($name,$tmpname,$filetype,$filesize,$error=0){  
     
    $this->setOption('TmpName', $tmpname); 
    $this->setOption('OrgiName', $name); 
    $arrstr=explode('.', $name); 
    $this->setOption('FileType', $arrstr[count($arrstr)-1]);      
    $this->setOption('FileSize', $filesize); 
    return true; 
  } 
  /** 
   +------------------------------------------------------------------------- 
   * 检查上传路径函数 
   +------------------------------------------------------------------------- 
   * @return boolean 
   */ 
  private function CheckPath(){ 
    if(empty($this->filepath)){ 
      $this->setOption('ErrorNum', -5); 
      return false; 
    } 
    if (!file_exists($this->filepath)||!is_writable($this->filepath)) { 
       if (!@mkdir($this->filepath,0755)) { 
         $this->setOption('ErrorNum',-4); 
         return false; 
       } 
    } 
    return true; 
  } 
  private function Is_Http_Post(){ 
    if (!is_uploaded_file($this->tmpname)) { 
      $this->setOption('ErrorNum',-6);  
      return false; 
    }else{ 
      return true; 
    } 
  } 
  /** 
   +-------------------------------------------------------------------- 
   *检查文件尺寸函数 
   +-------------------------------------------------------------------- 
   * @return boolean 
   */ 
  private function CheckSize(){ 
    if ($this->filesize>$this->maxsize) { 
      $this->setOption('ErrorNum', -2); 
      return false; 
    }else{ 
      return true; 
    } 
  } 
  /** 
   +--------------------------------------------------------------- 
   * 检查文件类型函数 
   +--------------------------------------------------------------- 
   * @return boolean 
   */ 
  private function CheckType(){ 
    if (in_array($this->filetype, $this->allowtype)) { 
      return true; 
    }else{ 
      $this->setOption('ErrorNum', -1); 
      return false; 
    } 
  } 
  private function SetFileName(){ 
    if ($this->israndname) { 
      $this->setOption('NewName', $this->RandName()); 
    }else{ 
      $this->setOption('NewName',$this->orginame); 
    }  
  } 
  /** 
   +----------------------------------------------------------------- 
   * 获取新文件名 
   +------------------------------------------------------------------ 
   */ 
  public function getNewName() { 
    return $this->newname; 
  } 
  private function RandName(){ 
    $rule=date("YmdHis").rand(0, 999); 
    return $rule.'.'.$this->filetype; 
  } 
  private function MoveFile(){ 
    if ($this->errornum) { 
      $filepath=rtrim($this->filaepath,'/').'/'; 
      $filepath.=$this->newname; 
      if (@move_uploaded_file($this->tmpname,$filepath)) { 
        return true; 
       }else{ 
        $this->errormsg=$this->setOption('ErrorNum',-3 ); 
       } 
    }else{ 
      return false; 
    } 
  } 
  /** 
   +---------------------------------------------------------------- 
   * 错误信息函数 
   +---------------------------------------------------------------- 
   * @return string 
   */ 
   function getErrorNum() { 
    $erstr="上传文件<font color='red'>{$this->orginame}</font>出错"; 
    switch ($this->errornum) { 
      case 4: 
       $erstr.="没有文件被上传"; 
        break; 
      case 3: 
       $erstr.="文件只被部分上传"; 
        break; 
      case 2: 
       $erstr.="上传文件超过了HTML表单MAX_FILE_SIZE指定的值"; 
        break; 
      case 1: 
       $erstr.="上传文件超过了php.ini配置文件中upload_max_filesize的值"; 
        break; 
      case 0: 
       $erstr="上传{$this->orginame}成功"; 
        break;        
      case -1: 
       $erstr="未允许的类型"; 
        break; 
      case -2: 
       $erstr.="文件过大,不能超过{$this->maxsize}个字节";  
        break; 
      case -3: 
       $erstr.="上传失败"; 
        break; 
      case -4: 
       $erstr="创建上传目录失败,请重新指定上传目录"; 
        break; 
      case -5: 
       $erstr="未指定上传路径"; 
        break; 
      case -6: 
       $erstr="非法操作"; 
        break;                    
      default: 
       $erstr.="未知错误"; 
         
    } 
    return $erstr; 
  } 
 } 
&#63;> 

The above is the entire content of this article. I hope it will be helpful to everyone in learning PHP programming.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1127897.htmlTechArticleA very classic PHP file upload class sharing. File upload is a common function in project development, but file upload The process is rather cumbersome, as long as there are files uploaded, they need to be compiled...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

What is autoloading in PHP?What is autoloading in PHP?Apr 30, 2025 pm 03:37 PM

Autoloading in PHP automatically loads class files when needed, improving performance by reducing memory use and enhancing code organization. Best practices include using PSR-4 and organizing code effectively.

What are PHP streams?What are PHP streams?Apr 30, 2025 pm 03:36 PM

PHP streams unify handling of resources like files, network sockets, and compression formats via a consistent API, abstracting complexity and enhancing code flexibility and efficiency.

What is the maximum size of a file that can be uploaded using PHP ?What is the maximum size of a file that can be uploaded using PHP ?Apr 30, 2025 pm 03:35 PM

The article discusses managing file upload sizes in PHP, focusing on the default limit of 2MB and how to increase it by modifying php.ini settings.

What is Nullable types in PHP ?What is Nullable types in PHP ?Apr 30, 2025 pm 03:34 PM

The article discusses nullable types in PHP, introduced in PHP 7.1, allowing variables or parameters to be either a specified type or null. It highlights benefits like improved readability, type safety, and explicit intent, and explains how to declar

What is the difference between the unset() and unlink() functions ?What is the difference between the unset() and unlink() functions ?Apr 30, 2025 pm 03:33 PM

The article discusses the differences between unset() and unlink() functions in programming, focusing on their purposes and use cases. Unset() removes variables from memory, while unlink() deletes files from the filesystem. Both are crucial for effec

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools