A classic PHP file upload class to share _php instances

Source: Internet
Author: User
Tags php file upload
This article mainly introduces a classic PHP file upload class sharing, this article detailed comprehensive explanation of the file upload related requirements analysis and function implementation, and at the same time give the use of code, the need for friends can refer to the next

File upload is a common feature in project development, but the file upload process 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 in order to save development time, we typically encapsulate these reusable snippets into a class. To help developers in the future development, by writing a few simple code to achieve complex file upload function. For the weak foundation of the reader, as long as the use of the class can be, and some like the challenge of friends, you can try to read it, and can develop a own file upload class.

First, demand analysis

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

Second, the program design

Depending on the requirements of the program, we can declare 4 visible member properties for the file upload class, allowing the user to set some behavior when they use it. The required member properties are shown in the following table:

To avoid the value of an attribute being assigned some illegal values, these member properties need to be encapsulated, inaccessible outside the object, and assigned 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 parameter. After the set () method call is complete, the object ($this) is returned, so that, in addition to assigning values for each property individually, you can also perform a coherent operation to assign values to multiple properties. In this example, in addition to the set () method, the main thing is to implement the function of uploading files, so the system mainly provides some of the following public methods to achieve file upload operations, as shown in the following table:

To avoid the value of an attribute being assigned some illegal values, these member properties need to be encapsulated, inaccessible outside the object, and assigned 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 parameter. After the set () method call is complete, the object ($this) is returned, so that, in addition to assigning values for each property individually, you can also perform a coherent operation to assign values to multiple properties. In this example, in addition to the set () method, the main thing is to implement the function of uploading files, so the system mainly provides some of 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 is used to process the upload file, you can upload a file, you can also process multiple file uploads */class Fileuploa          d {Private $path = "./uploads"; Upload file save path Private $allowtype = array (' jpg ', ' gif ', ' PNG ');           Set restrictions on the type of upload file private $maxsize = 1000000;           Limit file Upload size (bytes) Private $israndname = true;              Sets whether to randomly rename the file, false not random private $originName;              Source file name Private $tmpFileName;               Temporary file name private $fileType;               File type (file suffix) private $fileSize;              File size private $newFileName;             New file name Private $errorNum = 0;             The error number Private $errorMess = "";  Error report message/** * used to set member properties ($path, $allowtype, $maxsize, $israndname) * Multiple property values can be set at once through a coherent operation * @param string $key member property name (case insensitive) * @param mixed $val The value set for the member property * @return Object returns its own object $this, which can be used for coherent operation */function set ($k       EY, $val) {$key = Strtolower ($key); if (Array_key_exists ($key, GET_CLAss_vars (Get_class ($this))) {$this->setoption ($key, $val);    } return $this; }/** * Call this method to upload a file * @param string $fileFile The form name of the uploaded file * @return bool If the upload succeeds return number true */F      Unction Upload ($fileField) {$return = true;        /* Check that the file path is a sticky/if (! $this->checkfilepath ()) {$this->errormess = $this->geterror ();      return false;      */* Send the file upload information 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, $file["name"] will be an array */if (Is_array ($name)) {$errors =array ();          /* Multiple file uploads are recycled, this loop only checks the upload file's role, and does not actually 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, re-start the properties of the attribute */if (! $return) $this->setfiles ();                if ($return) {/* holds the array of variables for all uploaded file names */$fileNames = array (); /* If multiple uploaded files are valid, upload files to the server via Ecstasy loop */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)) {/* first check the size and type */if ($this->checkfilesize () before uploading)             && $this->checkfiletype ()) {/* Set a new filename for the upload file */$this->setnewfilename ();            /* Upload file returns 0 for success, less than 0 for error */if ($this->copyfile ()) {return true;            }else{$return =false;          }}else{$return =false;         }} else {$return =false; }//If $return is false, the error message is saved in the property errormess if (! $return) $this->errormess= $this->geterror ()           ;      return $return; }}/** * get uploaded file name * @param void No parameters * @return string after uploading, the name of the new file, if it is multiple file upload return array */public    function GetFileName () {return $this->newfilename;    }/** * After the upload failed, call this method to return, upload error message * @param void no parameters * @return String Returns the information report of the upload file error, if it is a multi-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}</      font> error: ";        Switch ($this->errornum) {case 4: $str. = "No files were 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 value of the Upload_max_filesize option limit in php.ini";        Break Case-1: $str. = "type not allowed";        Break Case-2: $str. = "File is too large, the uploaded file cannot exceed {$this->maxsize} bytes";        Break Case-3: $str. = "Upload Failed";        Break Case-4: $str. = "Failed to set up the directory to upload files, please re-specify the upload directory";        Break Case-5: $str. = "The path of the uploaded file must be specified";        Break      Default: $str. = "Unknown error";    } return $str. ' <br> '; }/* settings and $_files related content */Private Function setfiles ($name = "", $tmp _name= "", $size =0, $error =0) {$this->setop      tion (' errornum ', $error);      if ($error) return false;      $this->setoption (' Originname ', $name); $thisSetOption (' Tmpfilename ', $tmp _name);      $ARYSTR = Explode (".", $name);      $this->setoption (' FileType ', Strtolower ($aryStr [Count ($ARYSTR)-1]));      $this->setoption (' fileSize ', $size);    return true;    }/* Sets the value for a single member property */Private Function setOption ($key, $val) {$this, $key = $val; }/* Set the file name after upload */private Function Setnewfilename () {if ($this->israndname) {$this->setoption (        ' NewFileName ', $this->prorandname ());      } else{$this->setoption (' NewFileName ', $this->originname); }/* Check whether the uploaded file is of a valid type */Private function Checkfiletype () {if (In_array (Strtolower ($this->filetype),      $this->allowtype)) {return true;        }else {$this->setoption (' ErrorNum ',-1);      return false;  }/* Check if the uploaded file is the allowed size */Private Function checkfilesize () {if ($this->filesize > $this->maxsize)        {$this->setoption (' ErrorNum ',-2); return false;      }else{return true; }/* Check to see if there is a directory where the uploaded files are stored */Private Function Checkfilepath () {if (Empty ($this->path)) {$this->set        Option (' 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 the Random file name */Private Function Prorandname () {$fileName = date (' Ymdhis '). "          _ ". Rand (100,999); Return $fileName. '. '.     $this->filetype; }/* Copy the upload file to the specified location */Private Function CopyFile () {if (! $this->errornum) {$path = RTrim ($this->pa Th, '/'). '        /';        $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

In this case, the file upload class FileUpload, that is, support single file upload, but also support multiple files to the server upload, there is no difference in the way of processing, but when the upload of the document, the upload must be an array of files to be passed to the server. The single file upload form looks like this:


<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>


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


<?php    //contains an upload class in a file upload class    include "fileupload.class.php";     $up = new FileUpload;    Set the properties (upload location, size, type, name is to be 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 an upload form the name of the PIC, if successful returns TRUE, the failure returns False if    ($up-Upload ("pic") {        echo ' < Pre> ';        Get uploaded file name sub        var_dump ($up->getfilename ());        Echo ' </pre> ';     } else {        echo ' <pre> ';        Get error message after upload failed        var_dump ($up->geterrormsg ());        Echo ' </pre> ';    }? >


In the upload.php file, you must first load the file to upload the FileUpload class that contains the file fileupload.class.php. Then instantiate the object of the file upload class, and then by calling the upload () method to upload the file, 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 report through the Geterrormsg () method. If you need to change some of the behavior of the upload, you can set some properties by calling the set () method. The set () method can be used to set the value of a property individually, and if you need to change the values of multiple properties, you can set it up by calling the set () method consecutively, or you can set multiple properties simultaneously with a coherent operation.

Download php File Upload class:

File Upload class. rar

Fileupload.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.