A classic php file upload class share _php instance

Source: Internet
Author: User
Tags html form php file upload
File upload is a relatively common function of project development, but the process of file upload is cumbersome, as long as there is a file upload where you need to write these complex code. In order to reduce the difficulty of writing functionality in each development, and to save development time, we typically encapsulate these reusable snippets of code into a class. Help developers in future development, by writing a few simple code will be able to achieve complex file upload function. For the weak foundation of the reader, as long as the use of this class can be, and for some friends who like to challenge, you can try to read it, and can develop a own file upload class.

I. Demand analysis

To the ball custom file upload class, that is, the use of very simple premise, but also can complete the following functions:
① supports single file uploads.
② supports multiple file uploads.
③ can specify the location of the upload file to save, you can set the size and type of upload file allowed, can be renamed by the system upload files, but also to set the original name of the upload file.
(Note: Require a single file upload and multiple file uploads to use the same mode of operation, some of the settings to upload will be the same way).

Second, program design

According to the requirements of the program requirements, we can declare the file upload Class 4 visible member properties, so that users can also do some behavior when using the settings. The required member properties are shown in the following table:

To avoid the value of a property being assigned some illegal value, you need to encapsulate these member properties, not accessible outside the object, and then assign values to the above four member properties through the set () method declared in the class. The set () method has two parameters, the first parameter is the member property name (case-insensitive), and the second argument is the value of the property in the preceding argument. After the set () method call is complete, this object ($this) is returned, so that in addition to assigning values to each property separately, you can assign values to multiple properties together in a coherent operation. In this example, in addition to the set () method, the most important is to implement the upload file function, so the system mainly provides the following public methods to achieve file upload operations, as shown in the following table:

To prevent the value of a property from being assigned some illegal value, you need to encapsulate these member properties, be inaccessible outside of the object, and assign values to the above four member properties by using the Set () method declared in the class. The set () method has two parameters, the first parameter is the member property name (case-insensitive), and the second argument is the value of the property in the preceding argument. After the set () method call is complete, this object ($this) is returned, so that in addition to assigning values to each property separately, you can assign values to multiple properties together in a coherent operation. In this example, in addition to the set () method, the most important is to implement the upload file function, so the system mainly provides the following public methods to achieve file upload operations, as shown in the following table:

<?php/** file:fileupload.class.php File Upload class FileUpload This class of instance object for processing upload files, can upload a file, can also handle multiple file upload/class Fil          eupload {Private $path = "./uploads"; Upload file save path Private $allowtype = array (' jpg ', ' gif ', ' PNG ');           Set the type of limit upload file private $maxsize = 1000000;           Limit file Upload size (bytes) Private $israndname = true;              Set whether to randomly rename the file, false not random private $originName;              source filename private $tmpFileName;               Temporary file name private $fileType;               File type (file suffix) private $fileSize;              File size private $newFileName;             New file name Private $errorNum = 0;             Error number Private $errorMess = ""; Error Reporting Message/** * Used to set member properties ($path, $allowtype, $maxsize, $israndname) * You can set multiple property values at once with a consistent operation * @param string $key member property name (case-insensitive) * @param mixed $val The value set for member properties * @return object returns to its own objects $this, which can be used for consecutive operations/FUNCTI 
      On set ($key, $val) {$key = Strtolower ($key); if (aRray_key_exists ($key, Get_class_vars (Get_class ($this))) {$this->setoption ($key, $val);
    return $this; 
 
    /** * Calls the method to upload the file * @param string $fileFile The form name of the upload file * @return bool If the upload successfully returns the number True * *
      function upload ($fileField) {$return = true;
        /* Check file path is a delay of legal * */if (! $this->checkfilepath ()) {$this->errormess = $this->geterror ();
      return false;
      * * Send the information of the file upload to the variable/$name = $_files[$fileField] [' name '];
      $tmp _name = $_files[$fileField] [' tmp_name '];
      $size = $_files[$fileField] [' size '];
 
      $error = $_files[$fileField] [' ERROR '];
        /* If multiple files are uploaded then $file["name" will be an array/if (Is_array ($name)) {$errors =array ();
          /* Multiple file uploads are recycled, this cycle only check the role of uploaded files, and did not really upload/for ($i = 0; $i < count ($name); $i + +) {/* Set file information/* 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 there is a problem, then restart the attribute * * (! $return) $this->setfiles ();      
          } if ($return) {///* Store all uploaded file name variable array/$fileNames = Array (); * * If the upload of multiple files are legitimate, then through ecstasy to upload files to the server * * 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;
          /* Upload a Single file processing method */Else {/* Set file information/if ($this->setfiles ($name, $tmp _name, $size, $error)) { * * Before uploading check the size and type */if ($this->checkfilesize () && $this->checkfiletype ()) {/* to upload files 
            Set new file name * * * $this->setnewfilename ();
            /* Upload file returns 0 for success, less than 0 are error/if ($this->copyfile ()) {return true;
            }else{$return =false;
          }}else{$return =false; 
        } else {$return =false; //If $return is false, error message is saved in property errormess if (! $return) $this->errormess= $this->geterro  
 
        R ();
      return $return;
    /** * Get uploaded file name * @param void No parameters * @return string upload, new file name, if multiple file upload return array * *
    Public Function GetFileName () {return $this->newfilename; /** * Upload failed, call the method then return, upload error letter* @param void No parameters * @return String returns an error in uploading the file report, if it is a multiple file upload return array/Public function geterrormsg () {
    return $this->errormess; * * Set upload error message/private function GetError () {$str = "Upload file <font color= ' red ' >{$this->originname}&
      lt;/font> error: ";
        Switch ($this->errornum) {case 4: $str. = "No file uploaded"; Case 3: $str. = "file is only partially uploaded";
        Break Case 2: $str. = "The size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form";
        Break Case 1: $str. = "The uploaded file exceeds the upload_max_filesize option limit in php.ini";
        Break Case-1: $str. = "Disallowed type";
        Break Case-2: $str. = "File is too large, upload file can not exceed {$this->maxsize} bytes";
        Break Case-3: $str. = "Upload Failed";
        Break Case-4: $str. = "Set up storage upload file directory failed, please specify the upload directory";
        Break Case-5: $str. = "The path to upload file must be specified";
        Break
      Default: $str. = "Unknown error";
    return $str. ' <br> '; /* Set and $_files related content/Private function setfiles ($name = "", $tmp _name= "", $size = 0,$error =0) {$this->setoption (' ErrorNum ', $error);
      if ($error) return false;
      $this->setoption (' Originname ', $name);
      $this->setoption (' Tmpfilename ', $tmp _name);
      $ARYSTR = Explode (".", $name);
      $this->setoption (' FileType ', Strtolower ($aryStr [Count ($ARYSTR)-1]);
      $this->setoption (' fileSize ', $size);
    return true;
    }/* Set value for individual member property/Private Function SetOption ($key, $val) {$this-> $key = $val; /* Set the file name after uploading * * Private Function Setnewfilename () {if ($this->israndname) {$this->setop  
      tion (' NewFileName ', $this->prorandname ());
      else{$this->setoption (' NewFileName ', $this->originname); }/* Check whether the uploaded file is a valid type/Private function Checkfiletype () {if (In_array strtolower ($this->filety
      PE), $this->allowtype)) {return true;
        }else {$this->setoption (' ErrorNum ',-1);
     return false; }/* Check whether the uploaded file is the allowable size/private function checkfilesize () {if ($this->filesize > $this->ma
        xsize) {$this->setoption (' ErrorNum ',-2);
      return false;
      }else{return true; }/* Check to see if there is a directory to store the uploaded files/private function Checkfilepath () {if (Empty ($this->path)) {$this-&
        Gt;setoption (' ErrorNum ',-5);
      return false;
          } if (!file_exists ($this->path) | | |!is_writable ($this->path)) {if (! @mkdir ($this->path, 0755)) {
          $this->setoption (' ErrorNum ',-4);
        return false;
    } return true; /* Set Random file name */Private Function Prorandname () {$fileName = date (' Ymdhis '). "    
      _ ". Rand (100,999); Return $fileName. '. 
    $this->filetype; /* Copy upload file to the specified location */Private Function CopyFile () {if (! $this->errornum) {$path = RTrim ($this-& Gt;path, '/'). '
        /'; $path. = $this->newfilenamE
        if (@move_uploaded_file ($this->tmpfilename, $path)) {return true;
          }else{$this->setoption (' ErrorNum ',-3);
        return false;
      } else {return false; }
    }
  }

IV. application process of File upload class

This example of the file upload class FileUpload, that is, support single file upload, but also support multiple files to the server upload, in the processing mode, there is no difference, but in the preparation of the upload standard, multiple file upload must be transmitted to the server as an array. The single file upload form looks like this:

<form action= "upload.php" method= "post" enctype= "Multipart/form-data" >
name: <input type= "text" name= "U Sername "value=" "/><br> <input type=" hidden "name=" max_file_size "
value=" 1000000 "/> Up
Pi C: <input type= "file" name= "pic[" "value=" "><br> up
Pic: <input type=" file "name=" pic["" value= "" &G T;<br> up
Pic: <input type= "file" Name= "pic[]" "value=" "><br> up
Pic: <input type=" fil E "name=" pic[] "value=" "><br>
<input type=" Submit "value=" upload "/><br>
& Lt;/form>

The above form points the submission to the same file upload.php, so it is easy to see that single and multiple file uploads are handled the same way, upload.php the code looks like this:

<?php     //contains an upload class in a file upload class     include "fileupload.class.php";
       $up = new FileUpload;
    //Set properties (upload location, size, type, name is randomly generated)      $up-> Set ("Path", "./images/");
     $up-> Set ("MaxSize", 2000000);
     $up-> Set ("Allowtype", Array ("GIF", "png", "JPG", "jpeg"));
     $up-> Set ("Israndname", false);       //using the Upload method in the object, you can upload the file, the method needs to pass a name of the upload form pic, if successful return true, failure return false      if ($up-> upload ("pic")) {        echo ' <pre> ';          //get uploaded file name         var_dump (
$up->getfilename ());
        echo ' </pre> ';   &NBSP;&NBSP;&NBSP;&NBSP} else {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSp;echo ' <pre> ';         //get error notification after upload failure        
 var_dump ($up->geterrormsg ());
        echo ' </pre> ';     }?>

In the upload.php file, you must first load the file to upload the file fileupload.class.php the FileUpload class resides in. Then instantiate the object of the file upload class, and then by calling upload () method upload file, if uploaded successfully, you can use the GetFileName () method to obtain the uploaded file name, if the upload failed, you can also through the geterrormsg () method to obtain error reports. If you need to change some of the behavior of the upload, you can complete some properties by calling the set () method. Set () methods can be used to set the value of a property alone, if you need to change the value of multiple properties, you can call the set () method to set up, you can continue to set multiple properties.

Download php File Upload class:

File Upload class. rar

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.