Home Backend Development PHP Tutorial A PHP file upload class sharing_php example

A PHP file upload class sharing_php example

Dec 05, 2017 am 09:09 AM
php upload share

This article mainly introduces a classic PHP file upload class sharing. This article explains in detail and comprehensively the requirements analysis and function implementation related to PHP file upload, and shares it at the same time. PHP code, friends who need it can refer to this article

File upload is a common function in project development, but the file upload process is more cumbersome, as long as there are files uploaded Wherever you need to write these complex codes. 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. Help developers in future development to implement complex file upload functions by writing a few simple codes. For readers with weak foundation, they only need to be able to use this class. For those who like challenges, they can try to understand it and develop a file upload class of their own.

1. Requirements Analysis

It is necessary to customize the file upload class, which can complete the following functions under the premise that it is very easy to use:
①Support single file upload.
 ②Support multiple file uploads.
 ③You can specify the storage location of the uploaded file yourself, you can set the size and type allowed for the uploaded file, you can rename the uploaded file by the system, and you can also set the original name of the uploaded file to be retained.
 (Note: It is required that single file upload and multiple file upload must use the same operation method, and some settings for upload must also use the same method).

2. Programming

According to the requirements of the program, we can declare 4 visible member attributes for the file upload class, so that users can You can also set some behaviors. The required member attributes are as shown in the following table:

In order to prevent the attribute values ​​from being assigned some illegal values, these member attributes need to be encapsulated and cannot be accessed outside the object. Then assign values ​​to the above four member attributes through the set() method declared in the class. The set() method has two parameters. The first parameter is the name of the member attribute (not case-sensitive), and the second parameter is the value corresponding to the attribute in the previous parameter. After the set() method is called, the object ($this) is returned. Therefore, in addition to assigning values ​​to each attribute individually, you can also perform consecutive operations to assign values ​​to multiple attributes together. In this example, in addition to the set() method, the most important thing is to implement the function of uploading files, so the system mainly provides the following public methods to implement file upload operations, as shown in the following table:

In order to prevent the attribute values ​​from being assigned some illegal values, these member attributes need to be encapsulated and cannot be accessed outside the object, and then the above four member attributes can be assigned values ​​through the set() method declared in the class. The set() method has two parameters. The first parameter is the name of the member attribute (not case-sensitive), and the second parameter is the value corresponding to the attribute in the previous parameter. After the set() method is called, the object ($this) is returned. Therefore, in addition to assigning values ​​to each attribute individually, you can also perform consecutive operations to assign values ​​to multiple attributes together. In this example, in addition to the set() method, the most important thing is to implement the function of uploading files, so the system mainly provides the following public methods to implement file upload operations, as shown in the following table:

<?php
  /** 
    file: fileupload.class.php 文件上传类FileUpload
    本类的实例对象用于处理上传文件,可以上传一个文件,也可同时处理多个文件上传
  */
  class FileUpload { 
    private $path = "./uploads";          //上传文件保存的路径
    private $allowtype = array(&#39;jpg&#39;,&#39;gif&#39;,&#39;png&#39;); //设置限制上传文件的类型
    private $maxsize = 1000000;           //限制文件上传大小(字节)
    private $israndname = true;           //设置是否随机重命名文件, false不随机
 
    private $originName;              //源文件名
    private $tmpFileName;              //临时文件名
    private $fileType;               //文件类型(文件后缀)
    private $fileSize;               //文件大小
    private $newFileName;              //新文件名
    private $errorNum = 0;             //错误号
    private $errorMess="";             //错误报告消息
 
    /**
     * 用于设置成员属性($path, $allowtype,$maxsize, $israndname)
     * 可以通过连贯操作一次设置多个属性值
     *@param  string $key  成员属性名(不区分大小写)
     *@param  mixed  $val  为成员属性设置的值
     *@return  object     返回自己对象$this,可以用于连贯操作
     */
    function set($key, $val){
      $key = strtolower($key); 
      if( array_key_exists( $key, get_class_vars(get_class($this) ) ) ){
        $this->setOption($key, $val);
      }
      return $this;
    }
 
    /**
     * 调用该方法上传文件
     * @param  string $fileFile  上传文件的表单名称 
     * @return bool        如果上传成功返回数true 
     */
 
    function upload($fileField) {
      $return = true;
      /* 检查文件路径是滞合法 */
      if( !$this->checkFilePath() ) {       
        $this->errorMess = $this->getError();
        return false;
      }
      /* 将文件上传的信息取出赋给变量 */
      $name = $_FILES[$fileField][&#39;name&#39;];
      $tmp_name = $_FILES[$fileField][&#39;tmp_name&#39;];
      $size = $_FILES[$fileField][&#39;size&#39;];
      $error = $_FILES[$fileField][&#39;error&#39;];
 
      /* 如果是多个文件上传则$file["name"]会是一个数组 */
      if(is_Array($name)){    
        $errors=array();
        /*多个文件上传则循环处理 , 这个循环只有检查上传文件的作用,并没有真正上传 */
        for($i = 0; $i < count($name); $i++){ 
          /*设置文件信息 */
          if($this->setFiles($name[$i],$tmp_name[$i],$size[$i],$error[$i] )) {
            if(!$this->checkFileSize() || !$this->checkFileType()){
              $errors[] = $this->getError();
              $return=false; 
            }
          }else{
            $errors[] = $this->getError();
            $return=false;
          }
          /* 如果有问题,则重新初使化属性 */
          if(!$return)          
            $this->setFiles();
        }
 
        if($return){
          /* 存放所有上传后文件名的变量数组 */
          $fileNames = array();      
          /* 如果上传的多个文件都是合法的,则通过销魂循环向服务器上传文件 */
          for($i = 0; $i < count($name); $i++){ 
            if($this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i] )) {
              $this->setNewFileName(); 
              if(!$this->copyFile()){
                $errors[] = $this->getError();
                $return = false;
              }
              $fileNames[] = $this->newFileName;  
            }          
          }
          $this->newFileName = $fileNames;
        }
        $this->errorMess = $errors;
        return $return;
      /*上传单个文件处理方法*/
      } else {
        /* 设置文件信息 */
        if($this->setFiles($name,$tmp_name,$size,$error)) {
          /* 上传之前先检查一下大小和类型 */
          if($this->checkFileSize() && $this->checkFileType()){ 
            /* 为上传文件设置新文件名 */
            $this->setNewFileName(); 
            /* 上传文件  返回0为成功, 小于0都为错误 */
            if($this->copyFile()){ 
              return true;
            }else{
              $return=false;
            }
          }else{
            $return=false;
          }
        } else {
          $return=false; 
        }
        //如果$return为false, 则出错,将错误信息保存在属性errorMess中
        if(!$return)
          $this->errorMess=$this->getError();  
 
        return $return;
      }
    }
 
    /** 
     * 获取上传后的文件名称
     * @param  void   没有参数
     * @return string 上传后,新文件的名称, 如果是多文件上传返回数组
     */
    public function getFileName(){
      return $this->newFileName;
    }
 
    /**
     * 上传失败后,调用该方法则返回,上传出错信息
     * @param  void   没有参数
     * @return string  返回上传文件出错的信息报告,如果是多文件上传返回数组
     */
    public function getErrorMsg(){
      return $this->errorMess;
    }
 
    /* 设置上传出错信息 */
    private function getError() {
      $str = "上传文件<font color=&#39;red&#39;>{$this->originName}</font>时出错 : ";
      switch ($this->errorNum) {
        case 4: $str .= "没有文件被上传"; break;
        case 3: $str .= "文件只有部分被上传"; break;
        case 2: $str .= "上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值"; break;
        case 1: $str .= "上传的文件超过了php.ini中upload_max_filesize选项限制的值"; break;
        case -1: $str .= "未允许类型"; break;
        case -2: $str .= "文件过大,上传的文件不能超过{$this->maxsize}个字节"; break;
        case -3: $str .= "上传失败"; break;
        case -4: $str .= "建立存放上传文件目录失败,请重新指定上传目录"; break;
        case -5: $str .= "必须指定上传文件的路径"; break;
        default: $str .= "未知错误";
      }
      return $str.&#39;<br>&#39;;
    }
 
    /* 设置和$_FILES有关的内容 */
    private function setFiles($name="", $tmp_name="", $size=0, $error=0) {
      $this->setOption(&#39;errorNum&#39;, $error);
      if($error)
        return false;
      $this->setOption(&#39;originName&#39;, $name);
      $this->setOption(&#39;tmpFileName&#39;,$tmp_name);
      $aryStr = explode(".", $name);
      $this->setOption(&#39;fileType&#39;, strtolower($aryStr[count($aryStr)-1]));
      $this->setOption(&#39;fileSize&#39;, $size);
      return true;
    }
 
    /* 为单个成员属性设置值 */
    private function setOption($key, $val) {
      $this->$key = $val;
    }
 
    /* 设置上传后的文件名称 */
    private function setNewFileName() {
      if ($this->israndname) {
        $this->setOption(&#39;newFileName&#39;, $this->proRandName());  
      } else{ 
        $this->setOption(&#39;newFileName&#39;, $this->originName);
      } 
    }
 
    /* 检查上传的文件是否是合法的类型 */
    private function checkFileType() {
      if (in_array(strtolower($this->fileType), $this->allowtype)) {
        return true;
      }else {
        $this->setOption(&#39;errorNum&#39;, -1);
        return false;
      }
    }
 
    /* 检查上传的文件是否是允许的大小 */
    private function checkFileSize() {
      if ($this->fileSize > $this->maxsize) {
        $this->setOption(&#39;errorNum&#39;, -2);
        return false;
      }else{
        return true;
      }
    }
 
    /* 检查是否有存放上传文件的目录 */
    private function checkFilePath() {
      if(empty($this->path)){
        $this->setOption(&#39;errorNum&#39;, -5);
        return false;
      }
      if (!file_exists($this->path) || !is_writable($this->path)) {
        if (!@mkdir($this->path, 0755)) {
          $this->setOption(&#39;errorNum&#39;, -4);
          return false;
        }
      }
      return true;
    }
 
    /* 设置随机文件名 */
    private function proRandName() {    
      $fileName = date(&#39;YmdHis&#39;)."_".rand(100,999);    
      return $fileName.&#39;.&#39;.$this->fileType; 
    }
 
    /* 复制上传文件到指定的位置 */
    private function copyFile() {
      if(!$this->errorNum) {
        $path = rtrim($this->path, &#39;/&#39;).&#39;/&#39;;
        $path .= $this->newFileName;
        if (@move_uploaded_file($this->tmpFileName, $path)) {
          return true;
        }else{
          $this->setOption(&#39;errorNum&#39;, -3);
          return false;
        }
      } else {
        return false;
      }
    }
  }
Copy after login

4. Application process of file upload class

The file upload class FileUpload in this example supports single file upload and multiple files at the same time. There is no difference in the processing method when uploading to the server. However, when writing an upload bid, multiple file uploads must be passed to the server in an array. The single file upload form is as follows:

<form action="upload.php" method="post" enctype="multipart/form-data" >
    name: <input type="text" name="username" value="" /><br>
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
    up pic: <input type="file" name="pic[]" value=""><br>
    up pic: <input type="file" name="pic[]" value=""><br>
    up pic: <input type="file" name="pic[]" value=""><br>
    up pic: <input type="file" name="pic[]" value=""><br>
 
    <input type="submit" value="upload" /><br>
 
</form>
Copy after login

The above forms all point the submission location to the same file upload.php, so it is not difficult to see that the single and Multiple file uploads are processed in the same way. The upload.php code is as follows:

<?php
    //包含一个文件上传类中的上传类
    include "fileupload.class.php";
 
    $up = new fileupload;
    //设置属性(上传的位置, 大小, 类型, 名是是否要随机生成)
    $up -> set("path", "./images/");
    $up -> set("maxsize", 2000000);
    $up -> set("allowtype", array("gif", "png", "jpg","jpeg"));
    $up -> set("israndname", false);
 
    //使用对象中的upload方法, 就可以上传文件, 方法需要传一个上传表单的名子 pic, 如果成功返回true, 失败返回false
    if($up -> upload("pic")) {
        echo &#39;<pre class="brush:php;toolbar:false">&#39;;
        //获取上传后文件名子
        var_dump($up->getFileName());
        echo &#39;
'; } else { echo '
&#39;;
        //获取上传失败以后的错误提示
        var_dump($up->getErrorMsg());
        echo &#39;
'; } ?>
Copy after login

In the upload.php file, it must first be loaded File upload FileUpload class is located in the file fileupload.class.php. Then instantiate the object of the file upload class, and then upload the file by calling the upload() method. If the upload is successful, you can get the uploaded file name through the getFileName() method. If the upload fails, you can also get the error through the getErrorMsg() method. Report. If you need to change some upload behaviors, you can complete the setting of some attributes by calling the set() method. The set() method can be used alone to set the value of an attribute. If you need to change the values ​​of multiple attributes, you can call the set() method continuously to set it, or you can set multiple attributes at the same time in a continuous operation.

related suggestion:

PHP encapsulated multi-file upload class examples and usage details

##PHP file upload analysis

php Sample code sharing for file upload

The above is the detailed content of A PHP file upload class sharing_php example. For more information, please follow other related articles on the PHP Chinese website!

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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles