Detailed explanation of file upload and download examples using PHP

王林
Release: 2023-04-07 10:54:02
forward
2999 people have browsed it

1. Upload principle and configuration

1.1 Principle

Upload the client file to the server, and then move the server-side file (temporary file) to the specified Directory is enough.

1.2 Client configuration

Required: form page (select upload file);

Specifically: the sending method isPOST, addenctype="multipart/form-data"Attributes, both are indispensable (however, both advantages and disadvantages coexist, here also limits the upload method and subsequent calls to the uploaded file, etc., which will be discussed later

    Insert title here 
请选择您要上传的文件:
Copy after login

First is the form page (please ignore the front-end issues automatically...), the key is the attributes of the form; the other is the use of type="file" in the input (reflecting the powerful expansion of PHP, etc.) .

Then doAction.php


        
Copy after login

First look at the informationprint_r($_FILES)

Array ( [myFile] => Array ( [name] => 梁博_简历.doc [type] => application/msword [tmp_name] => D:\wamp\tmp\php1D78.tmp [error] => 0 [size] => 75776 ) )
Copy after login

So what you get is a two-dimensional array , how to use it, are all basic things (in fact, I like to reduce the dimension and then use it);

is basically something that can be understood at a glance, not wordy, there are two key points:tmp_nameTemporary file name;errorError message (code name, can be used later);

Then let’s take a look at the last part of doAction and use the error message to feed back to the user. What needs to be explained is why the error is reported. And the error message is nothing

1.3 About the error report

--The reason for the error

basically exceeds or does not comply with the server’s requirements for uploading files Configuration, so what are the server-side configurations?

First consider what we use for uploading? POST, upload

So look for these items in php.ini:

file_upload:On

upload_tmp_dir=——Temporary file saving directory;

upload_max_filesize=2M

max_file_uploads=20——The maximum number of files allowed to be uploaded at one time (note the difference from the one above, whether there is a size, don’t think about it)

post_max_size=8M ——The maximum value for sending data in post mode

Other related configurations

max_exectuion_time=-1——Maximum execution time to avoid poor programs Occupying server resources;

max_input_time=60

max_input_nesting_level=64——Input nesting depth;

memory_limit=128M——The maximum independent memory usage of a single thread

In short, it is all related to the configuration of resources.

--Error number

UPLOAD_ERR_OKValue: 0; No error occurred and the file was uploaded successfully.
UPLOAD_ERR_INI_SIZEValue: 1; The uploaded file exceeds the limit of the upload_max_filesize option in php.ini.
UPLOAD_ERR_FORM_SIZEValue: 2; The size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form.
UPLOAD_ERR_PARTIALValue: 3; Only part of the file is uploaded.
UPLOAD_ERR_NO_FILEValue: 4; No file was uploaded.

Note: This error message is the information uploaded in the first step, that is, uploaded to a temporary folder, not the case of move or copy.

2. Upload related restrictions

2.1 Client restrictions

请选择您要上传的文件:
Copy after login

Here the input attributes are used to control the size and type of uploaded files. There are restrictions, but personal feelings: first, the html code is "visible"; second, it often doesn't work (I haven't found the reason, but because of the first one I also want to give up on it, just know it.

2.2 Server-side restrictions

Mainly limit size and type, and then the method.

$maxsize) { exit("上传文件过大!"); } if (!in_array($ext, $allowExt)) { exit("非法文件类型"); } if (!is_uploaded_file($tmp_name)) { exit("上传方式有误,请使用post方式"); } if (@move_uploaded_file($tmp_name, $uniName)) {//@错误抑制符,不让用户看到警告 echo "文件".$filename."上传成功!"; }else{ echo "文件".$filename."上传失败!"; } //判断是否为真实图片(防止伪装成图片的病毒一类的 if (!getimagesize($tmp_name)) {//getimagesize真实返回数组,否则返回false exit("不是真正的图片类型"); } }else{ switch ($error){ case 1: echo "超过了上传文件的最大值,请上传2M以下文件"; break; case 2: echo "上传文件过多,请一次上传20个及以下文件!"; break; case 3: echo "文件并未完全上传,请再次尝试!"; break; case 4: echo "未选择上传文件!"; break; case 7: echo "没有临时文件夹"; break; } }
Copy after login

2.3 Encapsulation

Function

$maxSize) { exit("上传文件过大!"); } if (!in_array($ext, $allowExt)) { exit("非法文件类型"); } if (!is_uploaded_file($tmp_name)) { exit("上传方式有误,请使用post方式"); } //判断是否为真实图片(防止伪装成图片的病毒一类的 if (!getimagesize($tmp_name)) {//getimagesize真实返回数组,否则返回false exit("不是真正的图片类型"); } if (@move_uploaded_file($tmp_name, $destination)) {//@错误抑制符,不让用户看到警告 echo "文件".$filename."上传成功!"; }else{ echo "文件".$filename."上传失败!"; } }else{ switch ($error){ case 1: echo "超过了上传文件的最大值,请上传2M以下文件"; break; case 2: echo "上传文件过多,请一次上传20个及以下文件!"; break; case 3: echo "文件并未完全上传,请再次尝试!"; break; case 4: echo "未选择上传文件!"; break; case 7: echo "没有临时文件夹"; break; } } return $destination; }
Copy after login

Call


        
Copy after login

3. Implementation of uploading multiple files

3.1 Use single file encapsulation

    Insert title here 
请选择您要上传的文件:
请选择您要上传的文件:
请选择您要上传的文件:
请选择您要上传的文件:
Copy after login

        
Copy after login

The idea here is fromprint_r($_FILES)Find it, print it out and you will see that it is a two-dimensional array. It is very simple, just traverse it and use it!

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){
Copy after login

Like this, Simple is simple, but there are some problems.

It is no problem to upload 4 pictures normally, but if the exit in the function is activated in the middle, it will stop immediately, causing other pictures to be unable to be uploaded.

3.2 Upgraded version of encapsulation

Aims to implement encapsulation for multiple or single file uploads

First write a static file like this

    Insert title here 
请选择您要上传的文件:
请选择您要上传的文件:
请选择您要上传的文件:
请选择您要上传的文件:
Copy after login

Print You can get a three-dimensional array by clicking $_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 ) ) )
Copy after login

.

It’s complicated, but it’s complicated in a regular way. The values are all together, which is very convenient for us to get values! !

So first get the file information and turn it into a single file processing information

function getFiles(){ $i=0; foreach($_FILES as $file){ if(is_string($file['name'])){ //单文件判定 $files[$i]=$file; $i++; }elseif(is_array($file['name'])){ foreach($file['name'] as $key=>$val){ //我的天,这个$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; }
Copy after login

Then if there is an exit error like before, just change the exit. 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;//1M //判断错误号 $res=array(); if($fileInfo['error']===UPLOAD_ERR_OK){ //检测上传得到小 if($fileInfo['size']>$maxSize){ $res['mes']=$fileInfo['name'].'上传文件过大'; } $ext=getExt($fileInfo['name']); //检测上传文件的文件类型 if(!in_array($ext,$allowExt)){ $res['mes']=$fileInfo['name'].'非法文件类型'; } //检测是否是真实的图片类型 if($flag){ if(!getimagesize($fileInfo['tmp_name'])){ $res['mes']=$fileInfo['name'].'不是真实图片类型'; } } //检测文件是否是通过HTTP POST上传上来的 if(!is_uploaded_file($fileInfo['tmp_name'])){ $res['mes']=$fileInfo['name'].'文件不是通过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'].'文件移动失败'; } $res['mes']=$fileInfo['name'].'上传成功'; $res['dest']=$destination; return $res; }else{ //匹配错误信息 switch ($fileInfo ['error']) { case 1 : $res['mes'] = '上传文件超过了PHP配置文件中upload_max_filesize选项的值'; break; case 2 : $res['mes'] = '超过了表单MAX_FILE_SIZE限制的大小'; break; case 3 : $res['mes'] = '文件部分被上传'; break; case 4 : $res['mes'] = '没有选择上传文件'; break; case 6 : $res['mes'] = '没有找到临时目录'; break; case 7 : case 8 : $res['mes'] = '系统错误'; break; } return $res; } }
Copy after login

It encapsulates two small ones

function getExt($filename){ return strtolower(pathinfo($filename,PATHINFO_EXTENSION)); } /** * 产生唯一字符串 * @return string */ function getUniName(){ return md5(uniqid(microtime(true),true)); }
Copy after login

Then in the static, use the multiple attribute to realize the input of multiple files


    Insert title here 
请选择您要上传的文件:
Copy after login

doAction6.php


'; $uploadFiles[]=@$res['dest']; } $uploadFiles=array_values(array_filter($uploadFiles)); //print_r($uploadFiles);
Copy after login

4. Object-oriented file upload

fileName=$fileName; $this->maxSize=$maxSize; $this->allowMime=$allowMime; $this->allowExt=$allowExt; $this->uploadPath=$uploadPath; $this->imgFlag=$imgFlag; $this->fileInfo=$_FILES[$this->fileName]; } /** * 检测上传文件是否出错 * @return boolean */ protected function checkError(){ if(!is_null($this->fileInfo)){ if($this->fileInfo['error']>0){ switch($this->fileInfo['error']){ case 1: $this->error='超过了PHP配置文件中upload_max_filesize选项的值'; break; case 2: $this->error='超过了表单中MAX_FILE_SIZE设置的值'; break; case 3: $this->error='文件部分被上传'; break; case 4: $this->error='没有选择上传文件'; break; case 6: $this->error='没有找到临时目录'; break; case 7: $this->error='文件不可写'; break; case 8: $this->error='由于PHP的扩展程序中断文件上传'; break; } return false; }else{ return true; } }else{ $this->error='文件上传出错'; return false; } } /** * 检测上传文件的大小 * @return boolean */ protected function checkSize(){ if($this->fileInfo['size']>$this->maxSize){ $this->error='上传文件过大'; return false; } return true; } /** * 检测扩展名 * @return boolean */ protected function checkExt(){ $this->ext=strtolower(pathinfo($this->fileInfo['name'],PATHINFO_EXTENSION)); if(!in_array($this->ext,$this->allowExt)){ $this->error='不允许的扩展名'; return false; } return true; } /** * 检测文件的类型 * @return boolean */ protected function checkMime(){ if(!in_array($this->fileInfo['type'],$this->allowMime)){ $this->error='不允许的文件类型'; return false; } return true; } /** * 检测是否是真实图片 * @return boolean */ protected function checkTrueImg(){ if($this->imgFlag){ if(!@getimagesize($this->fileInfo['tmp_name'])){ $this->error='不是真实图片'; return false; } return true; } } /** * 检测是否通过HTTP POST方式上传上来的 * @return boolean */ protected function checkHTTPPost(){ if(!is_uploaded_file($this->fileInfo['tmp_name'])){ $this->error='文件不是通过HTTP POST方式上传上来的'; return false; } return true; } /** *显示错误 */ protected function showError(){ exit(''.$this->error.''); } /** * 检测目录不存在则创建 */ protected function checkUploadPath(){ if(!file_exists($this->uploadPath)){ mkdir($this->uploadPath,0777,true); } } /** * 产生唯一字符串 * @return string */ protected function getUniName(){ return md5(uniqid(microtime(true),true)); } /** * 上传文件 * @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='文件移动失败'; $this->showError(); } }else{ $this->showError(); } } }
Copy after login
uploadFile(); echo $dest;
Copy after login

5. Download

    Insert title here 
下载1.rar
下载1.jpg
通过程序下载1.jpg
下载nv.jpg
Copy after login

        
Copy after login

总结:



二维数组的降维处理;

$_FILES变量

move_upload_file();copy();

tmp_name临时文件;

拓展名的提取;

真实图片的验证;

唯一文件名的生成;

函数封装以及调用;

利用单个文件函数实现多文件上传;

小功能的封装;

多文件的遍历;

面向对象的开发过程;

下载;

以上就是全部的讲解,希望可以帮助到大家,有错误的地方请指出。

更多相关问题请访问PHP中文网:PHP视频教程

The above is the detailed content of Detailed explanation of file upload and download examples using PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!