PHP file Upload class and PHP package of multi-File upload class sharing

Source: Internet
Author: User
Tags html form php file upload
This article is mainly to share with you PHP file upload class and PHP package of multi-file upload class related code, with a certain reference value, interested in small partners can refer to, hope to help everyone.


<?php$upload = new Upload (); $upload->uploadfile (' FM ');/* Print error message *///var_dump ($upload->errornumber);//Var_  Dump ($upload->errorinfo); class upload{//File upload path protected $path = ' upload/';  Allow file upload suffix protected $allowSuffix = [' jpg ', ' jpeg ', ' gif ', ' wbmp ', ' PNG '];  MIME type protected $allowMime =[' image/jpg ', ' image/jpeg ', ' image/gif ', ' image/wbmp ', ' image/png '];  Allowed upload size protected $maxSize = 2000000;  Whether to enable the default prefix protected $isRandName =true;  The file prefix protected $prefix = ' up_ ';  Error number and error message protected $errorNumber;  protected $errorInfo;  File information//filename protected $oldName;  The suffix of the file protected $suffix;  The size of the file protected $size;  The MIME protected of the file $mime;  The path to the file's temporary file protected $tmpName;    File new name protected $newName; Construction method//Because the member property is more than the array to display the public function __construct ($arr =[]) {foreach ($arr as $key + $value) {$this->se    Toption ($key, $value); }}//Judge $key is not my member property, if it is set protected function setOption ($key, $value) {//Get all member properties $keys = Array_Keys (Get_class_vars (__class__));    if (In_array ($key, $keys)) {$this, $key = $value; }}//File Upload function//key is the value of the Name property in the Input box public function UploadFile ($key) {//To determine if there is no set path to the paths if (empty ($this->path)      ) {$this->setoption (' errornumber ',-1);    return false;      }//Determine if the path exists if writable if (! $this->check ()) {$this->setoption (' errornumber ',-2);     return false;    }//To determine if the error message inside the $_files is 0, if 0 then the file information can be obtained directly on the server side, the extracted information is saved to the member properties $error = $_files[$key [' Error '];      if ($error) {$this->setoption (' ErrorNumber ',-3);    return false;    }else {//Extract file-related information and save to member properties $this->getfileinfo ($key); }//Determine if the file size, mime, and suffix are in accordance with if (! $this->checksize () | |! $this->checkmime () | |! $this->checksuffix ()) {Retu     RN false;    }//Get new file name $this->newname = $this->createnewname (); Determine if the file is being uploaded and is moving the upload file if (is_uploaded_file ($this->tmpname)) {if (Move_uploaded_file ($this->tmpname, $this-&gt ;p Ath. $this-&Gt;newname) {return $this->path. $this->newname;        }else {$this->setoption (' errornumber ',-7);      return false;      }}else{$this->setoption (' errornumber ',-6);    return false; }}//detects if a folder exists, is writable protected function check () {//folder does not exist or is not a directory. Create Folder if (!file_exists ($this->path) | |!    Is_dir ($this->path)) {return mkdir ($this->path,0777,true);    }//Determine if the file is writable if (!is_writeable ($this->path)) {return chmod ($this->path, 0777);  } return true;    }//Get file information according to key protected function GetFileInfo ($key) {//Get the name of the file $this->oldname = $_files[$key] [' name '];    Get the MIME type of the file $this->mime = $_files[$key [' type '];    Temporary documents obtained $this->tmpname = $_files[$key] [' tmp_name '];    Get file size $this->size = $_files[$key [' size '];  Get the file suffix $this->suffix = pathinfo ($this->oldname) [' extension ']; }//Determine file size protected function Checksize () {if ($this->size > $this->maxsize) {$This->setoption (' ErrorNumber ',-3);    return false;  } return true; }//To determine the MIME type protected function Checkmime () {if (!in_array ($this->mime, $this->allowmime)) {$this->setop      tion (' errornumber ',-4);    return false;  } return true; }//Judgment suffix protected function checksuffix () {if (!in_array ($this->suffix, $this->allowsuffix)) {$this->set      Option (' ErrorNumber ',-5);    return false;  } return true; }//Create new name protected function Createnewname () {if ($this->israndname) {$name = $this->prefix.uniqid ().    $this->suffix;    }else {$name = $this->prefix. $this->oldname;  } return $name;    Public Function __get ($name) {if ($name = = ' ErrorNumber ') {return $this->errornumber;    }elseif ($name = = ' ErrorInfo ') {return $this->geterrorinfo ();      }} protected function GetErrorInfo () {switch ($this->errornumber) {case-1: $str = ' file path not set ';    Break Case-2: $str= ' file is not a directory or not writable ';    Break      Case-3: $str = ' file exceeds the specified size ';    Break      Case-4: $str = ' MIME type not compliant ';    Break      Case-5: $str = ' file suffix not compliant ';    Break      Case-6: $str = ' not upload file ';    Break      Case-7: $str = ' move failed ';    Break      Case 1: $str = ' exceeds ini set size ';    Break      Case 2: $str = ' exceeds HTML form size ';    Break      Case 3: $str = ' article only partially uploaded ';    Break      Case 4: $str = ' no file upload ';    Break      Case 6: $str = ' temporary file not found ';    Break      Case 7: $str = ' file write Failed ';    Break  } return $STR; }}


<!doctype html>

Note:the name in input must be the same as the value in the UploadFile in the upload Class!

PHP encapsulated Multi-File upload class examples and usage explained:

<?php/**//* * @ (#) uploadfile.php * * Can process the user multiple upload files simultaneously. The validated file is saved to the specified directory after validation. * You can return useful information about uploading files for use by other programs. (such as file name, type, size, save path) * Use method see the bottom of this class (UploadFile class use note) information.  * */class UploadFile {var $user _post_file = Array ();//user uploaded file Var $save _file_path;   The path of storing the user upload file var $max _file_size;   Maximum file size var $last _error; Record last error message//default allows user to upload file type var $allow _type = array (' gif ', ' jpg ', ' png ', ' zip ', ' rar ', ' txt ', ' Doc ', ' pdf '); var $final _file_path; The final saved file name var $save _info = Array (); Returns a set of useful information that is used to prompt the user. /**//** * constructor, with initialization related information, user to upload files, storage path, etc. * @param Array $file user uploaded file * @param String $path Store the path of user uploaded file * @param Integer $  Size allows the user to upload a file (in bytes) * @param array $type This array holds the file type uploaded by the user of the allowable meter */function UploadFile ($file, $path, $size = 2097152, $type = {$this->user_post_file = $file; $this->save_file_path = $path; $this->max_file_size = $size;//If the user does not fill in the file size, The default is 2M. if ($type! = ") $this->allow_type = $type; /**//** * Store users upload files, verify the legality passed, save to the specified location. * @access public * @return int value is 0 o'clock upload failed, non 0 indicates the number of successful uploads. */function upload () {for ($i = 0; $i < count ($this->user_post_file[' name '); $i + +) {//If the current file upload function, perform the next step.  if ($this->user_post_file[' error '] [$i] = = 0) {//Take the current file name, temporary file name, size, extension, which will be used later.  $name = $this->user_post_file[' name ' [$i];  $tmpname = $this->user_post_file[' tmp_name ' [$i];  $size = $this->user_post_file[' size ' [$i];  $mime _type = $this->user_post_file[' type ' [$i];  $type = $this->getfileext ($this->user_post_file[' name '] [$i]);  Detects whether the current upload file size is legitimate. if (! $this->checksize ($size)) {$this->last_error = "The file size is too big.   File name is: ". $name;   $this->halt ($this->last_error);  Continue  }//detects if the current upload file name extension is valid. if (! $this->checktype ($type)) {$this->last_error = "unallowable file type:.". $type. "   File name is: ". $name;   $this->halt ($this->last_error);  Continue  }//detects if the current upload file is being submitted illegally. if (!is_uploaded_file ($tmpname)) {$this->last_error = "Invalid Post file method.   File name is: ". $name; $this->halt ($this->lAST_ERROR);  Continue  }//After moving the file, rename the file with. $basename = $this->getbasename ($name, ".".  $type); The file name after the move $saveas = $basename. " -". Time ().".  $type; Save the new file name to the specified directory, format: Store path + file name + time + extension $this->final_file_path = $this->save_file_path. "  /". $saveas; if (!move_uploaded_file ($tmpname, $this->final_file_path)) {$this->last_error = $this->user_post_file['   Error '] [$i];   $this->halt ($this->last_error);  Continue  }//stores information about the current file for other programs to call. $this->save_info[] = Array ("name" = = $name, "type" = = $type, "mime_type" = = $mime _type, "si  Ze "= $size," saveas "= $saveas," path "= $this->final_file_path); }} return count ($this->save_info); Returns the number of files successfully uploaded}/**//** * Return some useful information for use elsewhere. * @access public * @return Array returns the final saved path */function Getsaveinfo () {return $this->save_info;}/**//** * Detects user commit file size is No legal * @param Integer $size The size of the uploaded file by the user * @access Private * @return Boolean if true to indicate the size is legal, or vice versa * * function Checksize ($size) {if ($size > $this->max_file_size) {return false;} else {return true;}}/**//** * Detect user Submissions The type of the piece is legal * @access Private * @return Boolean if true to indicate that the type is legal and vice versa */function Checktype ($extension) {foreach ($this->all Ow_type as $type) {if (strcasecmp ($extension, $type) = = 0) return true;} return false; /**//** * Display error message * @param $msg error message to display * @access private */function Halt ($msg) {printf ("<b><uploadfile Erro R:></b>%s <br>\n ", $msg); }/**//** * Fetch file extension * @param string $filename given file name to take extension * @access private * @return String returns the given file extension */function GetFile EXT ($filename) {$stuff = PathInfo ($filename); return $stuff [' extension '];}/**//** * takes the given file file name, excluding the extension. * Eg:getbasename ("j:/hexuzhong.jpg"); Returns Hexuzhong * * @param string $filename given file name to be taken * @access private * @return String returns the file name */function Getbasename ($fi Lename, $type) {$basename = basename ($filename, $type); return $basename;}} /**//******************** UploadFileClass using comments//note, upload component The Name property is used in the array form, whether one or more, such as: <input type= "file" Name= "user_upload_file[]" ><input type= "file" Name= "user_upload_file[]" >//if the user clicked the Upload button. if ($_post[' action '] = = "Upload") {//Set the type of file that the user is allowed to upload. $type = Array (' gif ', ' jpg ', ' png ', ' zip ', ' rar '); Instantiate the upload class, the first parameter is the file group that the user uploads, the second parameter is the storage path,//The third parameter is the maximum size of a file. If not, the default is 2M//The fourth parameter is an array of types that are allowed to be uploaded by a user. If not, the default is GIF, JPG, PNG, zip, rar, txt, doc, pdf $upload = new UploadFile ($_files[' user_upload_file '), ' j:/tmp ', 100000, $ty PE); Upload the user file, return an int value, for the number of uploaded files successfully. $num = $upload->upload (); if ($num! = 0) {echo "Upload successful <br>";//Get information about the file, file name, type, size, path. Print it out with Print_r (). Print_r ($upload->getsaveinfo ());    Format: Array//(//[0] = = Array (//[Name] = example.txt//[Type] = TXT//[size] = 526/// [Path] = j:/tmp/example-1108898806.txt//)//) echo $num. " File upload Success "; } else {echo "Upload failed <br>";}} */?>

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.