PHP implements file upload/download instance _ php instance

Source: Internet
Author: User
Tags php file upload temporary file storage unsupported
This article mainly introduces the PHP file upload and download instance. This article describes in detail the requirements and functions of file upload, and provides the code, for more information, see. PHP file upload and download this article introduces PHP file upload and download. now I will share it with you and give you a reference. Let's take a look at it with Xiaobian.

I. Upload principle and configuration

Principle 1.1

Upload the client file to the server, and then move the server file (temporary file) to the specified directory.

1.2 client configuration

Required: form page (Select Upload file );

Specifically, the sending method is POST and The enctype = "multipart/form-data" attribute is added. Both are indispensable (but both advantages and disadvantages coexist, this also limits the upload method and call after the uploaded file, which will be discussed later)

 Insert title here<?php?>

First, the form page (ignore front-end issues automatically ...), The key is the form attribute. In addition, type = "file" is used in input (which reflects the powerful extensions of php and so on ).

Then 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 the temporary files on the server to the specified location // method 1 move_upload_file ($ tmp_name, $ destination) // move_uploaded_file ($ tmp_name, "uploads /". $ filename); // The folder should be created in advance, or an error will be reported. // method 2 copy ($ src, $ des) // The above two functions return true successfully, otherwise, false // copy ($ tm P_name, "copies /". $ filename); // note that you cannot perform operations on temporary files in both methods. the temporary file seems to be gone after the operation is complete. let's try to copy ($ tmp_name, "copies /". $ filename); move_uploaded_file ($ tmp_name, "uploads /". $ filename); // can be implemented, indicating that the move function is basically equivalent to cutting; copy is copy, the temporary file is still //, and the error message is different, if ($ error = 0) {echo "Upload successful! ";}Else {switch ($ error) {case 1: echo" exceeds the maximum value of the uploaded file. upload a file below 2 MB "; break; case 2: echo "too many files are uploaded. please upload 20 or fewer files at a time! "; Break; case 3: echo" the file is not completely uploaded. please try again! "; Break; case 4: echo" file not selected! "; Break; case 5: echo" uploading file is 0 "; break ;}}

Let's take a look at print_r ($ _ FILES ).

Array ([myFile] => Array ([name] => Liang Bo _ .doc [type] => application/msword [tmp_name] => D: \ wamp \ tmp \ php1D78. tmp [error] => 0 [size] => 75776 ))

So what we get is a two-dimensional array. how to use it is a basic thing (in fact, I like to use it for dimensionality reduction );

There are two key points: temporary tmp_name file name; error message (code name, which can be used later );

Next, let's take a look at the latter part of doAction, which uses the error message to feedback to the user. we need to explain why the error is reported and what the error message is;

1.3 Error Reporting

-- Error cause:

Basically, they all exceed or do not comply with the server's file upload configuration. What are the server-side configurations?

First, consider what we use for uploading? POST, upload

So in php. ini, find the following items:

File_upload: On

Upload_tmp_dir = -- temporary file storage directory;

Upload_max_filesize = 2 M

Max_file_uploads = 20 -- maximum number of files that can be uploaded at a time (note the difference with the previous one and whether there is a size. Don't worry about it)

Post_max_size = 8 M -- maximum value of data sent in post mode

Other configurations

Max_exectuion_time =-1 -- the maximum execution time to prevent programs from occupying server resources;

Max_input_time = 60

Max_input_nesting_level = 64 -- input nested depth;

Memory_limit = 128 M -- Maximum independent memory usage of a single thread

In all, resource configuration is related.

-- Error number

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

  • UPLOAD_ERR_ OK value: 0; no error occurs. the file is uploaded successfully.
  • UPLOAD_ERR_INI_SIZE: 1; the uploaded file exceeds the limit of the upload_max_filesize option 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 file is uploaded.

Note: this error message is the information uploaded in the first step, that is, the information uploaded to the temporary folder, rather than the move or copy information.

II. Upload restrictions

2.1 client restrictions

 

Here, the input attribute is used to limit the size and type of the uploaded file, but I personally think: 1. the html code is "visible"; 2. it often does not work (no reason is found, but because I also want to give up the first one, you just need to know.

2.2 Server restrictions

It mainly limits the size and type, and then the method.

<? Phpheader ('content-type: text/html; charset = utf-8 '); // receives 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"]; // Set the server limit to $ maxsize = 10485760; // 10 M, 10*1024*1024 $ allowExt = array ('jpeg ', 'jpg', 'PNG ', 'tif '); // specifies the file type that can be uploaded (extended name $ ext = pathinfo ($ filename, PATHINFO_EXTENSION); // extracts the extended name of the uploaded file // The destination information $ path = "Uploads"; if (! File_exists ($ path) {// when the directory does not exist, create the directory mkdir ($ path, 0777, true); chmod ($ path, 0777 );} // $ destination = $ path. "/". $ filename; // get a unique file name! Avoid overwriting $ uniName = md5 (uniqid (microtime (true), true) due to the same file name )). $ ext; // md5 encryption. uniqid generates a unique id. the microtime prefix is if ($ error = 0) {if ($ size> $ maxsize) {exit ("the uploaded file is too large! ");} If (! In_array ($ ext, $ allowExt) {exit ("invalid file type");} if (! Is_uploaded_file ($ tmp_name) {exit ("incorrect Upload method, please use post method");} if (@ move_uploaded_file ($ tmp_name, $ uniName )) {// @ error blocker to prevent users from seeing the warning echo "file ". $ filename. "Upload successful! ";}Else {echo" file ". $ filename." Upload failed! ";}// Determine whether the image is a real image (if (! Getimagesize ($ tmp_name) {// getimagesize returns an array; otherwise, false exit ("not a real image type") is returned;} else {switch ($ error) {case 1: echo "exceeds the maximum size of the file to be uploaded. please upload files below 2 MB"; break; case 2: echo "too many files to be uploaded. please upload 20 and below files at a time! "; Break; case 3: echo" the file is not completely uploaded. please try again! "; Break; case 4: echo" file not selected! "; Break; case 7: echo" no temporary folder "; break ;}} here, the specific implementation is annotated, and each step can be done by yourself

2.3 encapsulation

Function

<? Phpfunction uploadFile ($ fileInfo, $ path, $ allowExt, $ maxSize) {$ filename = $ fileInfo ["name"]; $ tmp_name = $ fileInfo ["tmp_name"]; $ size = $ fileInfo ["size"]; $ error = $ fileInfo ["error"]; $ type = $ fileInfo ["type"]; // limits $ ext = pathinfo ($ filename, PATHINFO_EXTENSION) on the server side. // 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 ("the uploaded file is too large! ");} If (! In_array ($ ext, $ allowExt) {exit ("invalid file type");} if (! Is_uploaded_file ($ tmp_name) {exit ("incorrect Upload method, please use post method ");} // Determine whether the image is a real image (if (! Getimagesize ($ tmp_name) {// getimagesize returns an array, otherwise false exit ("not a real image type");} if (@ move_uploaded_file ($ tmp_name, $ destination) {// @ error blocker to prevent users from seeing the warning echo "file ". $ filename. "Upload successful! ";}Else {echo" file ". $ filename." Upload failed! ";}} Else {switch ($ error) {case 1: echo" exceeds the maximum value of the file to be uploaded. Upload files below 2 MB "; break; case 2: echo "too many files are uploaded. please upload 20 or fewer files at a time! "; Break; case 3: echo" the file is not completely uploaded. please try again! "; Break; case 4: echo" file not selected! "; Break; case 7: echo" no temporary 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);

III. multifile Upload implementation

3.1 encapsulation using a single file

 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);}

The idea here is to find it from print_r ($ _ FILES) and print it to see that it is a two-dimensional array. it's easy to use it through traversal!

Change the definition of the function above and give some default values.

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

This is simple, but has some problems.

It is okay to upload the four images normally, but if the exit function is activated in the middle, it will stop immediately, and other images cannot be uploaded.

3.2 Upgrade package

It is designed to encapsulate 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        )      [size] => Array        (          [0] => 46174          [1] => 46174          [2] => 34196          [3] => 38514        )    ))

You can get a 3D array.

The complexity is complicated, but the complexity is regular, and the values are all together. it is very convenient for us to take the value !!

So first, get the file information and convert it to the information processed by a single file.

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, diao $ files [$ I] ['name'] = $ file ['name'] [$ key] for $ 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 ;}

Then change the exit to the previous exit error. use res here.

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; // 1 M // judgment error code $ res = array (); if ($ fileInfo ['error'] = UPLOAD_ERR_ OK) {// detect if ($ fileInfo ['size']> $ maxSize) {$ res ['Mes '] = $ fileInfo ['name'] after uploading. 'upload file too large ';} $ ext = getExt ($ fileInfo ['name']); // checks the file type of the uploaded file if (! In_array ($ ext, $ allowExt) {$ res ['Mes '] = $ fileInfo ['name']. 'invalid file type';} // checks whether the image type is true if ($ flag) {if (! Getimagesize ($ fileInfo ['tmp _ name']) {$ res ['Mes '] = $ fileInfo ['name']. 'Not real Image type';} // checks whether the object is uploaded through http post. if (! Is_uploaded_file ($ fileInfo ['tmp _ name']) {$ res ['Mes '] = $ fileInfo ['name']. 'file not uploaded through 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 moving failed';} $ res ['Mes '] = $ fileInfo ['name']. 'uploaded successfully'; $ res ['dest'] = $ destination; return $ res;} else {// Match error message switch ($ fileInfo ['error']) {case 1: $ res ['Mes '] = 'the uploaded file exceeds the value of the upload_max_filesize option in the PHP configuration file'; break; case 2: $ res ['Mes '] = 'size beyond the size limit of form MAX_FILE_SIZE'; break; case 3: $ res ['Mes '] = 'upload part of file'; break; case 4: $ res ['Mes '] = 'file not selected'; break; case 6: $ res ['Mes'] = 'no temporary directory found '; break; case 7: case 8: $ res ['Mes '] = 'system error'; break;} return $ res ;}}

It encapsulates 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 ));}

In the static state, the multiple attribute is used to input multiple files;

 Insert title heredoAction6<?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);

In this way, several files can be uploaded in a relatively powerful process-oriented way (learning is called a sad ...);

4. object-oriented file Upload

<? Php class upload {protected $ fileName; protected $ maxSize; protected $ allowMime; protected $ allowExt; protected $ uploadPath; protected $ partition; 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];}/*** check whether an error occurred while uploading FILES * @ return boo Lean */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 by MAX_FILE_SIZE in the form '; break; case 3: $ this-> error = 'File partially upload'; break; case 4: $ this-> error = 'upload file not selected'; break; case 6: $ this-> error = 'temporary directory not found '; break; case 7: $ this-> error = 'file not writeable '; break; case 8: $ this-> error =' due to PHP extension Interrupted file uploads in sequence '; break;} return false;} else {return true ;}} else {$ this-> error = 'File Upload error'; return false ;}} /*** check the size of the uploaded file * @ return boolean */protected function checkSize () {if ($ this-> fileInfo ['size']> $ this-> maxSize) {$ this-> error = 'upload file is too large '; return false;} return true;}/*** check extension * @ return boolean */protected function checkExt () {$ this-> ext = strtolower (pathinfo ($ this-> fileInfo ['name'], PATHINFO_EX TENSION); if (! In_array ($ this-> ext, $ this-> allowExt) {$ this-> error = 'unsupported extension '; return false;} return true ;} /*** check file type ** @ return boolean */protected function checkMime () {if (! In_array ($ this-> fileInfo ['type'], $ this-> allowMime) {$ this-> error = 'unsupported file type '; return false ;} return true;}/*** check whether the image is real * @ return boolean */protected function checkTrueImg () {if ($ this-> imgFlag) {if (! @ Getimagesize ($ this-> fileInfo ['tmp _ name']) {$ this-> error = 'not a real image'; return false;} return true ;}} /*** check whether the * @ return boolean */protected function checkHTTPPost () {if (! Is_uploaded_file ($ this-> fileInfo ['tmp _ name']) {$ this-> error = 'file not uploaded through http post '; return false ;} return true;}/*** display error */protected function showError () {exit (''. $ this-> error. '');}/*** create */protected function checkUploadPath () {if (! File_exists ($ this-> uploadPath) {mkdir ($ this-> uploadPath, 0777, true );}} /*** generate 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-> 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 ($ this-> fileInfo ['tmp _ name'], $ this-> destination) {return $ this-> destination ;} else {$ this-> error = 'File movement 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;

4. Download

If the browser does not know anything, you can download it directly. if the browser does not know anything, you need to take one or two more steps.

 Insert title hereDownload 1.rar
Download 1.jpg
Download 1.jpg through the program
Download nv.jpg <? Php?><? Php $ filename = $ _ GET ['filename']; header ('content-disposition: attachment; filename = '. basename ($ filename); header ('content-length :'. filesize ($ filename); readfile ($ filename );

Thank you for reading this article. I hope it will help you. thank you for your support for this site!

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.