国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
A very classic PHP file upload class sharing,
Home Backend Development PHP Tutorial Very classic PHP file upload class sharing, _PHP tutorial

Very classic PHP file upload class sharing, _PHP tutorial

Jul 12, 2016 am 08:51 AM
php

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; //錯誤信息 
/** 
 +------------------------------------------------------------------------------ 
 *構造函數(shù) 
 +------------------------------------------------------------------------------ 
 * @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;  
   } 
  } 
  /** 
   +------------------------------------------------------------------------ 
   *設置類屬性值函數(shù) 
   +------------------------------------------------------------------------ 
   * @param mix $key 
   * @param mix $value 
   */ 
  private function setOption($key,$value){ 
    $key=strtolower($key); 
    $this->$key=$value; 
  } 
  /** 
   +--------------------------------------------------------------------------- 
   * 獲取文件變量參數(shù)函數(shù) 
   +--------------------------------------------------------------------------- 
   * @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; 
  } 
  /** 
   +------------------------------------------------------------------------- 
   * 檢查上傳路徑函數(shù) 
   +------------------------------------------------------------------------- 
   * @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; 
    } 
  } 
  /** 
   +-------------------------------------------------------------------- 
   *檢查文件尺寸函數(shù) 
   +-------------------------------------------------------------------- 
   * @return boolean 
   */ 
  private function CheckSize(){ 
    if ($this->filesize>$this->maxsize) { 
      $this->setOption('ErrorNum', -2); 
      return false; 
    }else{ 
      return true; 
    } 
  } 
  /** 
   +--------------------------------------------------------------- 
   * 檢查文件類型函數(shù) 
   +--------------------------------------------------------------- 
   * @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; 
    } 
  } 
  /** 
   +---------------------------------------------------------------- 
   * 錯誤信息函數(shù) 
   +---------------------------------------------------------------- 
   * @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}個字節(jié)";  
        break; 
      case -3: 
       $erstr.="上傳失敗"; 
        break; 
      case -4: 
       $erstr="創(chuàng)建上傳目錄失敗,請重新指定上傳目錄"; 
        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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

How do I validate user input in PHP to ensure it meets certain criteria? How do I validate user input in PHP to ensure it meets certain criteria? Jun 22, 2025 am 01:00 AM

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

What is data serialization in PHP (serialize(), unserialize())? What is data serialization in PHP (serialize(), unserialize())? Jun 22, 2025 am 01:03 AM

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

How do I embed PHP code in an HTML file? How do I embed PHP code in an HTML file? Jun 22, 2025 am 01:00 AM

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

See all articles