PHP implementation of File upload and download examples and summary _php instances

Source: Internet
Author: User
Tags md5 encryption
first, the upload principle and configuration

1.1 Principle

Upload the client files to the server side, and then move the server-side files (temporary files) to the specified directory.

1.2 Client Configuration

Required: Form page (select Upload file);

Specifically: Send to post, add enctype= "Multipart/form-data" attribute, both are indispensable (however, the advantages and disadvantages coexist, here also limits the way of uploading and upload the file after the call, etc.)

 
  Insert Title here<?php?>

First form page (please automatically ignore front-end issues ...) ), the key is the property of the form, and also the use of the type= "file" in input (which manifests the powerful expansion of PHP, etc.).

And then the doaction.

<?php//$_files: File Upload variable//print_r ($_files); $filename =$_files[' myFile ' [' Name ']; $type =$_files[' myFile ' [' type ']; $tmp _name=$_files[' myFile ' [' tmp_name ']; $size =$_files[' myFile '] [' size '] ; $error =$_files[' myFile ' [' Error '];//move temporary files on the server to the specified location//method one Move_upload_file ($tmp _name, $destination)//move_ Uploaded_file ($tmp _name, "uploads/". $filename);//folder should be established in advance, otherwise error//Method two copy ($SRC, $des)//above two functions are successfully returned true, otherwise return false// Copy ($tmp _name, "copies/". $filename);//Note that the temporary file cannot be manipulated by both methods, the temporary file appears to be out of operation, and we try to copy it in reverse ($tmp _name, "copies/". $ filename); Move_uploaded_file ($tmp _name, "uploads/". $filename);//Can be implemented, indicating that the move function is basically the equivalent of cut; copy is copy, temporary file is still in// Error messages are not the same, encountered errors can be viewed or directly reported to the user if ($error ==0) {echo "Upload success! ";}      else{switch ($error) {case 1:echo "exceeds the maximum uploaded file, please upload 2M files below";    Break Case 2:echo "Uploading too many files, please upload 20 files at a time!"      ";    Break Case 3:echo "The file is not fully uploaded, please try again!"      ";    Break Case 4:echo "Upload File not selected!      ";    Break      Case 5:echo "Upload file is 0";  Break }}

Take a look at the Print_r ($_files) message first.

Array (  [myFile] = = Array    (      [Name] = Liangbo _ cv. doc      [Type] = Application/msword      [Tmp_name] = > D:\wamp\tmp\php1D78.tmp      [ERROR] = 0      [size] = 75776    ))

So get a two-dimensional array, how to use, are basic things (in fact, I like to reduce the dimension and reuse);

Basic is a glance to understand things, not wordy, the key has two: Tmp_name temporary file name; error message (code name, can be used later);

Then take a look at the back part of the doaction, using the error message to feedback to the user, need to explain why the error, and the error message is what all;

1.3 About Error

--Cause of error

Basically is more than or does not conform to the server about the upload file configuration, then what is the server-side configuration?

First consider uploading what we use? Post,upload

So look for these items in the php.ini:

file_upload:onupload_tmp_dir=--temporary file save directory; upload_max_filesize=2mmax_file_uploads=20--maximum number of files allowed to upload at one time (note the difference between There's no size, don't think about it. The maximum value of the data sent by the Post_max_size=8m--post method

Other related configurations

max_exectuion_time=-1--maximum execution time, avoid the application of server resources;

Max_input_time=60

max_input_nesting_level=64--input nesting depth;

memory_limit=128m--maximum single-thread independent memory usage

This is all about the configuration of the resource.

--Error number

The following (lazy) quoted from http://blog.sina.com.cn/s/blog_3cdfaea201008utf.html

UPLOAD_ERR_OK value: 0; No error occurred and the file upload was successful.
Upload_err_ini_size value: 1; The uploaded file exceeds the value of the Upload_max_filesize option limit in php.ini.
Upload_err_form_size value: 2; The size of the uploaded file exceeds the value specified by the Max_file_size option in the HTML form.
Upload_err_partial value: 3; Only part of the file is uploaded.
Upload_err_no_file value: 4; No files were uploaded.

Note: This error message is the first step to upload the information, that is, upload to the temporary folder, not the situation of move or copy.

Second, upload the relevant restrictions

2.1 Client Throttling

There is a restriction on the size and type of the uploaded file using the input attribute, but the personal feeling: first, the HTML code is "visible", and the second, often does not work (not found the reason, but because the first I also want to abandon it, know is good.

2.2 Server-side throttling

The main limit is size and type, and then there is the way.

<?phpheader (' content-type:text/html;charset=utf-8 ');//Accept the file, temporary file information $fileinfo=$_files["MyFile"];//reduced-dimension operation $ Filename= $fileinfo ["name"]; $tmp _name= $fileinfo ["Tmp_name"]; $size = $fileinfo ["size"]; $error = $fileinfo ["Error"];$ Type= $fileinfo ["type"];//server-side settings limit $maxsize=10485760;//10m,10*1024*1024$allowext=array (' jpeg ', ' jpg ', ' png ', ' TIF ') ;//Allow uploading of file types (extended name $ext=pathinfo ($filename, pathinfo_extension);//Extract the extension of the uploaded file//destination information $path= "uploads"; if (!file_exists (  $path)) {//When the directory does not exist, create a directory mkdir ($path, 0777,true); chmod ($path, 0777);} $destination = $path. " /". $filename;//Get a unique filename!  Prevents overwriting $uniname=md5 (Uniqid (Microtime (True), true) because of the same file name. $ext;//md5 encryption, Uniqid produces a unique id,microtime to do the prefix if ($error ==0) { if ($size > $maxsize) {exit ("Upload file too large!  ");  } if (!in_array ($ext, $allowExt)) {exit ("illegal file type");  if (!is_uploaded_file ($tmp _name)) {exit ("Incorrect upload method, please use post"); if (@move_uploaded_file ($tmp _name, $uniName)) {//@ error suppressor, do not let the user see the warning echo "file". $filename. " Upload succeeded! ";} else{echo "File". $filename. "  Upload failed! ";} Determine if it is a real picture (prevent masquerading as a pictureThe virus class if (!getimagesize ($tmp _name)) {//getimagesize true returns an array, otherwise returns false exit ("Not a true picture type");      }}else{switch ($error) {case 1:echo "exceeds the maximum uploaded file, please upload 2M files below";    Break Case 2:echo "Uploading too many files, please upload 20 files at a time!"      ";    Break Case 3:echo "The file is not fully uploaded, please try again!"      ";    Break Case 4:echo "Upload File not selected!      ";    Break      Case 7:echo "No temp folder";  Break }}

Here, the specific implementation has comments, each step can actually try it, very interesting.

2.3 Package

Function

<?phpfunction UploadFile ($fileInfo, $path, $allowExt, $maxSize) {$filename = $fileInfo ["name"]; $tmp _name= $fileInfo ["Tmp_name"]; $size = $fileInfo ["size"]; $error = $fileInfo ["error"]; $type = $fileInfo ["type"];//server-side setting limit $ext=pathinfo  ($filename, pathinfo_extension);//Purpose information if (!file_exists ($path)) {mkdir ($path, 0777,true); chmod ($path, 0777);} $uniName =md5 (Uniqid (Microtime (True), true)). '. '. $ext; $destination = $path. " /". $uniName, if ($error ==0) {if ($size > $maxSize) {exit (" Upload file too large!  ");  } if (!in_array ($ext, $allowExt)) {exit ("illegal file type");  if (!is_uploaded_file ($tmp _name)) {exit ("Incorrect upload method, please use post");  }//To determine whether it is a real picture (!getimagesize ($tmp _name) {//getimagesize true return array, otherwise false exit ("Not a true picture type") (prevent the virus masquerading as a picture); if (@move_uploaded_file ($tmp _name, $destination)) {//@ error suppressor, do not let the user see the warning echo "file". $filename. " Upload succeeded! ";} else{echo "File". $filename. " Upload failed! ";}}      else{switch ($error) {case 1:echo "exceeds the maximum uploaded file, please upload 2M files below";    Break Case 2:echo "Uploading too many files, please upload 20 files at a time!"    ";  Break Case 3:echo "The file is not fully uploaded, please try again!"      ";    Break Case 4:echo "Upload File not selected!      ";    Break      Case 7:echo "No temp folder";  Break }}return $destination;}

Call

<?phpheader (' Content-type:text/html;charset=utf-8 '); $fileInfo =$_files["MyFile"; $maxSize =10485760;//10m,10* 1024*1024$allowext=array (' jpeg ', ' jpg ', ' png ', ' TIF '); $path = "uploads"; Include_once ' upfunc.php '; UploadFile ($ FileInfo, $path, $allowExt, $maxSize);

Three, multi-file upload implementation

3.1 Using a single file package

 
  Insert Title here
<?php//print_r ($_files); header (' Content-type:text/html;charset=utf-8 '); include_once ' upfunc.php '; foreach ($_ FILES as $fileInfo) {  $file []=uploadfile ($fileInfo);}

Here the idea, from Print_r ($_files) to find, print out to see is a two-dimensional array, very simple, traverse to use is good!

The definition of the function above changes, given some default values

function UploadFile ($fileInfo, $path = "uploads", $allowExt =array (' jpeg ', ' jpg ', ' png ', ' TIF '), $maxSize =10485760) {

In this way, simplicity is simple, but some problems are encountered.

Normal upload of 4 images is OK, but if the middle activates the function of exit, it will stop immediately, resulting in other images can not be uploaded.

3.2 Upgrade Package

Designed for encapsulation of multiple or single file uploads

First, write a static file like this.

 
  Insert Title here

Print $_files

Array ([  myFile] = = Array ([      name] = + Array        (          [0] = Test32.png          [1] = = Test32.png          [2] = 333.png          [3] = = Test41.png        )      [Type] = = Array        (          [0] = Image/png          [1]          = = Image/png [2] = > Image/png          [3] = Image/png        )      [tmp_name] = = Array        (          [0] = D:\wamp\tmp\ Php831c.tmp          [1] = D:\wamp\tmp\php834C.tmp          [2] = D:\wamp\tmp\php837C.tmp          [3] = D:\wamp\tmp \php83bb.tmp        )      [ERROR] = Array        (          [0] = 0          [1] = 0          [2] = 0          [3] = 0< c29/>)      [size] = = Array        (          [0] = 46174          [1] = 46174          [2] = = 34196          [3] = = 38514)))    

You can get a three-dimensional array.

Complexity is complex, but the complexity of the law, the values are all together, it is convenient for us to take value!!

So get the file information and turn it into a single file to process that information.

function GetFiles () {  $i =0;  foreach ($_files as $file) {    if (is_string ($file [' name ')]) {//Single file determination      $files [$i]= $file;      $i + +;    } ElseIf (Is_array ($file [' name '])) {      foreach ($file [' name '] as $key = + $val) {//My days, this $key diao        $files [$i] Name ']= $file [' name '] [$key];        $files [$i] [' type ']= $file [' type '] [$key];        $files [$i] [' Tmp_name ']= $file [' tmp_name '] [$key];        $files [$i] [' ERROR ']= $file [' Error '] [$key];        $files [$i] [' Size ']= $file [' Size '] [$key];        $i + +      ;  }}} return $files;  }

And then the kind of exit mistake, just change the exit to the right, here with Res

function UploadFile ($fileInfo, $path = './uploads ', $flag =true, $maxSize =1048576, $allowExt =array (' jpeg ', ' jpg ', ' png ',  ' gif ') {//$flag =true;  $ALLOWEXT =array (' jpeg ', ' jpg ', ' gif ', ' PNG ');  $maxSize =1048576;//1m//Judgment Error number $res =array (); if ($fileInfo [' Error ']===upload_err_ok) {//Detect upload to get small if ($fileInfo [' Size ']> $maxSize) {$res [' mes ']= $fileInfo [' Nam E ']. '    Upload file too large ';    } $ext =getext ($fileInfo [' name ']); Detects the file type of the uploaded file if (!in_array ($ext, $allowExt)) {$res [' mes ']= $fileInfo [' name '].    illegal file type '; }//Detect if the true picture type if ($flag) {if (!getimagesize ($fileInfo [' tmp_name '])) {$res [' mes ']= $fileInfo [' name ']. '      Not a real picture type '; }}//detect if the file is uploaded via HTTP post (!is_uploaded_file ($fileInfo [' tmp_name '])) {$res [' mes ']= $fileInfo [' name '].    The file is not uploaded via HTTP post;    } if ($res) return $res;    $path = './uploads ';      if (!file_exists ($path)) {mkdir ($path, 0777,true);    chmod ($path, 0777);    } $uniName =getuniname (); $destination = $path. ' /'. $uniName. '.   $ext; if (!move_uploaded_file ($fileInfo [' Tmp_name '], $destination)) {$res [' mes ']= $fileInfo [' name ']. '    File move failed '; } $res [' Mes ']= $fileInfo [' name ']. '    Upload Success ';    $res [' dest ']= $destination;      return $res; }else{//Match error message switch ($fileInfo [' ERROR ']) {Case 1: $res [' mes '] = ' upload file exceeds php config file upload_max_filesiz        The value of the E option ';      Break        Case 2: $res [' mes '] = ' exceeds the size of the form max_file_size limit ';      Break        Case 3: $res [' mes '] = ' file part is uploaded ';      Break        Case 4: $res [' mes '] = ' no option to upload file ';      Break        Case 6: $res [' mes '] = ' No temporary directory found ';      Break        Case 7:case 8: $res [' mes '] = ' system error ';    Break  } return $res; }}

It's packed with two small

function Getext ($filename) {  return Strtolower (PathInfo ($filename, pathinfo_extension));} /** * Generates a unique string * @return string */function getuniname () {  return MD5 (Uniqid (Microtime (True), true));}

Then, in the static, the input of multiple files is implemented with the multiple property;

 
  Insert Title here

DoAction6

<?php//print_r ($_files); Header ("Content-type:text/html;charset=utf-8"); require_once ' upfunc2.php '; require_ Once ' common.func.php '; $files =getfiles ();//Print_r ($files); foreach ($files as $fileInfo) {  $res =uploadfile ($ FileInfo);  echo $res [' mes '], '
'; $uploadFiles []=@ $res [' dest '];} $uploadFiles =array_values (Array_filter ($uploadFiles));//print_r ($uploadFiles);

Such a few files, on the implementation of a more powerful process-oriented upload file function (learn to call a sad ...) );

Four, object-oriented file upload

(It's not a very written move ...) Stick to it first, and then again ...

<?php class upload{protected $fileName;  protected $maxSize;  protected $allowMime;  protected $allowExt;  protected $uploadPath;  protected $imgFlag;  protected $fileInfo;  protected $error;  protected $ext; /** * @param string $fileName * @param string $uploadPath * @param string $imgFlag * @param number $maxSize * @p Aram Array $allowExt * @param array $allowMime */Public function __construct ($fileName = ' MyFile ', $uploadPath = './uploa DS ', $imgFlag =true, $maxSize =5242880, $allowExt =array (' jpeg ', ' jpg ', ' png ', ' gif '), $allowMime =array (' image/jpeg ', '    Image/png ', ' image/gif ') {$this->filename= $fileName;    $this->maxsize= $maxSize;    $this->allowmime= $allowMime;    $this->allowext= $allowExt;    $this->uploadpath= $uploadPath;    $this->imgflag= $imgFlag;  $this->fileinfo=$_files[$this->filename];      /** * Detect error Uploading File * @return Boolean */protected function checkerror () {if (!is_null ($this->fileinfo)) { if ($this->fileinfo[' ERROR ']&Gt;0) {switch ($this->fileinfo[' error ') {Case 1: $this->error= ' exceeds the PHP configuration file upload_max_files            The value of the ize option ';          Break            Case 2: $this->error= ' exceeds the value of max_file_size set in the form ';          Break            Case 3: $this->error= ' file is partially uploaded ';          Break            Case 4: $this->error= ' no option to upload files ';          Break            Case 6: $this->error= ' no temporary directory found ';          Break            Case 7: $this->error= ' file is not writable ';          Break            Case 8: $this->error= ' due to PHP extension interrupt file Upload ';                    Break      } return false;      }else{return true;      }}else{$this->error= ' file On error ';    return false; }}/** * Detects the size of the uploaded file * @return Boolean */protected function checksize () {if ($this->fileinfo[' size ']> $thi      s->maxsize) {$this->error= ' upload file too large ';    return false;  } return true; }/** * Detect extension * @return boolEAN */protected function Checkext () {$this->ext=strtolower (pathinfo ($this->fileinfo[' name '],pathinfo_extensi    ON));      if (!in_array ($this->ext, $this->allowext)) {$this->error= ' disallowed extensions ';    return false;  } return true; }/** * Detects the type of file * @return Boolean */protected function Checkmime () {if (!in_array ($this->fileinfo[' type '), $t      His->allowmime) {$this->error= ' disallowed file type ';    return false;  } return true; }/** * Detects if it is a real picture * @return Boolean */protected function checktrueimg () {if ($this->imgflag) {if (! @geti        Magesize ($this->fileinfo[' Tmp_name ')) {$this->error= ' is not a real picture ';      return false;    } return true; }}/** * detects if an HTTP post is uploaded to the * @return Boolean */protected function Checkhttppost () {if (!is_uploaded_file ($this->fileinfo[' tmp_name '))      {$this->error= ' file is not uploaded via HTTP post ';    return false;  } return true; }/** * Display error */protected function ShowError () {exit ('  '); }/** * Detection directory does not exist then create */protected function Checkuploadpath () {if (!file_exists ($this->uploadpath)) {mkdir ($t    His->uploadpath,0777,true); }}/** * generates a unique string * @return String */protected function Getuniname () {return MD5 (Uniqid (Microtime (True), true)  ); /** * Upload file * @return String * * Public Function UploadFile () {if ($this->checkerror () && $this->che Cksize () && $this->checkext () && $this->checkmime () && $this->checktrueimg () &      & $this->checkhttppost ()) {$this->checkuploadpath ();      $this->uniname= $this->getuniname (); $this->destination= $this->uploadpath. ' /'. $this->uniname. '.      $this->ext;      if (@move_uploaded_file ($this->fileinfo[' tmp_name ', $this->destination)) {return $this->destination;        }else{$this->error= ' file move failed ';      $this->showerror ();    }}else{$this->showerror (); }}}<?php Header (' Content-type:Text/html;charset=utf-8 '); require_once ' upload.class.php '; $upload =new upload (' myFile1 ', ' Imooc '); $dest = $upload- >uploadfile (); Echo $dest;

Four, download

The browser does not know anything else, can be downloaded directly, but for the recognition, it takes one or two more steps

 
  Insert Title hereDownload 1.rar
Download 1.jpg
Download 1.jpg via program
Download nv.jpg<?php?><?php $filename =$_get[' filename '];header (' content-disposition:attachment;filename= '). BaseName ($filename)); header (' Content-length: '. FileSize ($filename)); ReadFile ($filename);

------------------Summary-----------------------



Dimensionality reduction for two-dimensional arrays;

$_files variable

move_upload_file (); copy ();

Tmp_name temporary files;

Extraction of extension names;

Validation of the real picture;

Generation of unique file names;

Function encapsulation and invocation;

Use a single file function for multi-file uploads;

Encapsulation of small functions;

Traversal of multiple files;

Object-oriented development process;

  • Related Article

    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.