This article introduces the PHP implementation file upload and download, now share to everyone, also give you a reference. Follow the small knitting to come and see.
First, the principle of uploading and configuration
1.1 Principle
Upload the client file 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);
In particular: Send the way for post, add enctype= "Multipart/form-data" attribute, both are indispensable (but, advantages and disadvantages coexist, here also limits the way to upload and upload the file after the call, etc., will be said later)
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
First form page (please automatically ignore front end problem ...) , the key is the property of form, and in addition, the type= "file" is used in input (which embodies 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 the error//Method two copy ($SRC, $des)//above two functions are successfully returned true, otherwise return false//copy ($tmp _name, "copies/". $filename);
Note that both methods do not operate on temporary files, the temporary file seems to run out of the operation, we try to copy ($tmp _name, "copies/". $filename);
Move_uploaded_file ($tmp _name, "uploads/". $filename); Can be implemented, that the move that function is basically equivalent to cut; copy is copy, temporary files are still in addition, 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 upload file, please upload 2M below file";
Break Case 2:echo "Upload file too much, please upload 20 files and the following file!"
";
Break Case 3:echo "File not fully uploaded, please try again!"
";
Break Case 4:echo "did not choose to upload file!"
";
Break
Case 5:echo "upload file for 0";
Break
}
}
First, take a look at the Print_r ($_files) message.
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 the basic things (in fact, I like to reduce the dimensions of the use);
Basic is the first thing to understand, not wordy, there are two key: Tmp_name temporary file name, error error message (code, can be used later);
And then look at the later part of the doaction, using the error information to feedback to the user, need to explain why the error, and error information is what all;
1.3 About the error
--The cause of the error:
are basically more than or do not conform to the server on the upload file configuration, then server-side configuration what?
Think about uploading first, what do we use? Post,upload
So find these items in the php.ini:
File_upload:on
upload_tmp_dir=--temporary file save directory;
Upload_max_filesize=2m
max_file_uploads=20--allows maximum number of files to be uploaded at one time (note the difference from the above, there is no size, don't think)
Post_max_size=8m--post the maximum value of sending data
Other related configurations
max_exectuion_time=-1--The maximum execution time, avoids the program to occupy the server resources;
Max_input_time=60
max_input_nesting_level=64--input nesting depth;
memory_limit=128m--independent memory usage for maximum single thread
This is all about the configuration of resources.
--Error number
The following (lazy) quote from http://blog.sina.com.cn/s/blog_3cdfaea201008utf.html
- UPLOAD_ERR_OK value: 0; No error occurred, file upload succeeded.
- 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 upload file exceeds the value specified by the Max_file_size option in the HTML form.
- Upload_err_partial value: 3; The file is only partially 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 situation, not move or copy of the case.
Second, upload related restrictions
2.1 Client Limits
<form action= "doaction2.php" method= "post" enctype= "Multipart/form-data" > <input type= "hidden" name= "
Max_file_size "value=" 101321 "/>
Please select the file you want to upload:
<input type= "File" Name= "MyFile" accept= "image/jpeg,image/gif,text/html"/><br/> <input type=
" Submit "value=" Upload "/>
</form>
Here use the attributes of the input to upload the file size and type of restrictions, but personal feeling: one, the HTML code is "visible"; second, often does not work (no reason, but because the first I want to give it, know it.)
2.2 Server-side limits
The main limit size and type, and then there is the way.
<?php header (' Content-type:text/html;charset=utf-8 ');
Accept files, temporary file information $fileinfo =$_files["myFile"];//dimension reduction Operation $filename = $fileinfo ["name"];
$tmp _name= $fileinfo ["Tmp_name"];
$size = $fileinfo ["Size"];
$error = $fileinfo ["Error"];
$type = $fileinfo ["type"]; Server-side setting restrictions $maxsize =10485760;//10m,10*1024*1024 $allowExt =array (' jpeg ', ' jpg ', ' png ', ' TIF ');//file type allowed to upload (name extension $ext =
PathInfo ($filename, pathinfo_extension);//extract uploaded file extension name//purpose Information $path = "uploads";
if (!file_exists ($path)) {//When directory does not exist, create directory mkdir ($path, 0777,true);
chmod ($path, 0777); }//$destination = $path. "
/". $filename; Get a unique filename!
Prevents overwriting $uniName =md5 (Microtime (True), true) because of the same file name. $ext;//md5 encryption, uniqid generate unique id,microtime do prefix if ($error ==0) { if ($size > $maxsize) {exit ("Upload file is too big!")
");
} if (!in_array ($ext, $allowExt)) {exit ("illegal file type");
} if (!is_uploaded_file ($tmp _name)) {exit ("Upload method is incorrect, please use POST method"); } if (@move_uploaded_file ($tmp _name, $uniName)) {//@ error suppressor, do not let the user see the warning echo "file". $filename. " Upload success! ";} else{echo "File". $fIlename. "
Upload failed! ";}
if (!getimagesize ($tmp _name)) {//getimagesize true returns an array, otherwise it returns false exit ("Not a true picture type") to determine whether it is a real picture (to prevent a virus masquerading as a picture).
}else{switch ($error) {case 1:echo "exceeds the maximum upload file, please upload 2M below file";
Break Case 2:echo "Upload file too much, please upload 20 files and the following file!"
";
Break Case 3:echo "File not fully uploaded, please try again!"
";
Break Case 4:echo "did not choose to upload file!"
";
Break
Case 7:echo "No temporary folder";
Break
Here, the concrete implementation has the annotation, each step actually can own
2.3 Package
Function
<?php function 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 Restrictions $ext =pathinfo ($filename, pathinfo_extension);
Objective 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 is too large!")
");
} if (!in_array ($ext, $allowExt)) {exit ("illegal file type");
} if (!is_uploaded_file ($tmp _name)) {exit ("Upload method is incorrect, please use POST method");
}//To determine if it is a true image (!getimagesize ($tmp _name) {//getimagesize A virus disguised as a picture) {The true return of the array, or false exit ("Not a true picture type"); } if (@move_uploaded_file ($tmp _name, $destination)) {//@ error suppressor, do not let the user see the warning echo "file". $filename. " Upload success! ";} else{echo "File". $filename. " Upload failed! ";}}
else{switch ($error) {case 1:echo "exceeds the maximum upload file, please upload 2M below file"; Break
Case 2:echo "Upload file too much, please upload 20 files and the following file!"
";
Break Case 3:echo "File not fully uploaded, please try again!"
";
Break Case 4:echo "did not choose to upload file!"
";
Break
Case 7:echo "No temporary folder";
Break
} return $destination;
}
Call
<?php
Header (' 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 Single file encapsulation
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Here's the idea, from Print_r ($_files) to look for, print out see is a two-dimensional array, very simple, traverse to use just fine!
Change the definition of the function above, 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 4 Pictures is no problem, but if the middle of the activation function in the exit, will immediately stop, resulting in other pictures can not upload.
3.2 Upgrade Package
Package designed to upload for multiple or single files
First, write a static file like this
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
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
)
[size] => Array
(
[0] => 46174
[1] => 46174< C36/>[2] => 34196
[3] => 38514))
You can get a three-dimensional array.
Complex is complex, but the complexity of the law, the values are together, it is convenient for us to take value!!
So first get the file information, become a single file processing that kind of information
function GetFiles () {
$i =0;
foreach ($_files as $file) {
if (is_string ($file [' name ')]) {//Single file decision
$files [$i]= $file;
$i + +;
} ElseIf (Is_array ($file [' name '])) {
foreach ($file [' name '] as $key => $val) {//My God, 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 exit error, just change the exit, here, 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 ['] Name ']. '
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 the real picture type '; }///test file is uploaded via HTTP post if (!is_uploaded_file ($fileInfo [' tmp_name ']) {$res [' mes ']= $fileInfo [' name '] ].'
The file is not uploaded via HTTP post mode ';
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{//Matching error message switch ($fileInfo [' ERROR ']) {Case 1: $res [' mes '] = ' upload file exceeds upload_max_fil in PHP config file
Value of the esize option ';
Break
Case 2: $res [' mes '] = ' exceeds the size of the form max_file_size limit ';
Break
Case 3: $res [' mes '] = ' file part uploaded ';
Break
Case 4: $res [' mes '] = ' no upload file selected ';
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));
}
/**
* produces unique string
* @return string
/
function Getuniname () {return
MD5 (Uniqid (Microtime (True), True ));
}
Then static, using multiple attribute to implement multiple file input;
<!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Such a few files, on the realization of a more powerful process-oriented upload file function (learn to call a sad ...) );
Iv. Object-oriented file upload
<?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 * @param array $allowExt * @param array $allowMime/Public function __construct ($fileName = ' MyFile ', $uploadPath = './uploads ', $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 upload File Error * @return Boolean/protected function CheckError () {if (!is_null ($this->fileinfo))
{ if ($this->fileinfo[' ERROR ']>0) {switch ($this->fileinfo[' error ')] {Case 1: $this-
>error= ' exceeds the value of the upload_max_filesize option in the PHP configuration file ';
Break
Case 2: $this->error= ' exceeds the value set in the form max_file_size ';
Break
Case 3: $this->error= ' file is partially uploaded ';
Break
Case 4: $this->error= ' did not choose to upload file ';
Break
Case 6: $this->error= ' did not find a temporary directory ';
Break
Case 7: $this->error= ' file is not writable ';
Break
Case 8: $this->error= ' due to PHP extensions interrupt file Upload ';
Break
return false;
}else{return true;
}else{$this->error= ' error on file ';
return false; }/** * Detects the size of uploaded files * @return Boolean/protected function checksize () {if ($this->fileinfo[' size ']& gt; $this->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_extension);
if (!in_array ($this->ext, $this->allowext)) {$this->error= ' disallowed extension ';
return false;
return true; /** * Detect File Type * @return Boolean/protected function Checkmime () {if (!in_array ($this->fileinfo[' Typ
E '], $this->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 (! @getimagesize ($this->fileinfo[' tmp_name '))
{$this->error= ' is not a real picture ';
return false;
return true; }/** * Detects whether the * @return Boolean/protected function Checkhttppost () {if (!is_upload) is uploaded via an HTTP POST method
Ed_file ($this->fileinfo[' Tmp_name ')) {$this->error= ' files are not uploaded via HTTP post;
return false;
return true; /** * Display Error/protected function ShowError () {exit (' <span style= ' color:red ' > '. $this->error. '
</span> '); /** * Detect directory does not exist create */protected function Checkuploadpath () {if (!file_exists ($this->uploadpath)) {MK
Dir ($this->uploadpath,0777,true); /** * produces 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-& Gt;checksize () && $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 ($thisfileinfo[' 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
For browsers do not know anything else, you can download directly, but for the ability to identify, need more than one or two steps
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
Thank you for reading, I hope to help you, thank you for your support for this site!