This article mainly introduces examples of file upload and download in PHP. This article explains in detail and comprehensively the demand analysis and function implementation related to file upload, and also provides the usage code. Friends who need it can refer to it.
PHP implements file upload and download
1. Upload principle and configuration
1.1 Principle
Upload client files to the server. Then move the server-side files (temporary files) to the specified directory.
1.2 Client configuration
Required: form page (select upload file);
Specifically: the sending method is POST, add enctype="multipart/form- data" attribute, both are indispensable (however, both advantages and disadvantages coexist, and the upload method and subsequent calling of the uploaded file are also limited here, which will be discussed later)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!DOCTYPE html>
<html>
<head>
<meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" >
<title>Insert title here</title>
</head>
<body>
<form action= "doAction.php" method= "post" enctype= "multipart/form-data" >
请选择您要上传的文件:
<input type= "file" name= "myFile" /><br/>
<input type= "submit" value= "上传" />
</form>
<?php
?>
</body>
</html>
|
Copy after login
The first is the form page (please ignore the front-end issues automatically...), the key is the attribute of form; the other is the use of type="file" in input (reflecting the power of PHP expansion, etc.).
Then doAction
##
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <?php
$filename = $_FILES ['myFile']['name'];
$type = $_FILES ['myFile']['type'];
$tmp_name = $_FILES ['myFile']['tmp_name'];
$size = $_FILES ['myFile']['size'];
$error = $_FILES ['myFile']['error'];
copy ( $tmp_name , "copies/" . $filename );
move_uploaded_file( $tmp_name , "uploads/" . $filename );
if ( $error ==0) {
echo "上传成功!" ;
} else {
switch ( $error ){
case 1:
echo "超过了上传文件的最大值,请上传2M以下文件" ;
break ;
case 2:
echo "上传文件过多,请一次上传20个及以下文件!" ;
break ;
case 3:
echo "文件并未完全上传,请再次尝试!" ;
break ;
case 4:
echo "未选择上传文件!" ;
break ;
case 5:
echo "上传文件为0" ;
break ;
}
}
|
Copy after login
First look at the information of print_r($_FILES)
1 2 3 4 5 6 7 8 9 10 11 12 | 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 is all basic things (in fact, I like to reduce the dimension and then use it);
It’s basically a glance Just understand things, not verbose, there are two key points: tmp_name temporary file name; error error message (code name, you can use it later);
Then let’s take a look at the last part of doAction, and use the error message to give feedback to Users, what needs to be explained is why the error is reported and what the error message is;
1.3 About error reporting
--The reason for the error reporting:
Basically They all exceed or do not comply with the server's configuration for uploading files. So what are the server-side configurations?
First consider uploading what we used? 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 above one, don’t think about it if there is a size)
post_max_size=8M——post method Maximum value of sent data
Other related configuration
max_exectuion_time=-1——Maximum execution time to avoid the program from occupying server resources;
max_input_time=60
max_input_nesting_level=64——Input nesting depth;
memory_limit=128M——Maximum independent memory usage of a single thread
In short, it is all about resources configuration.
--Error number
The following (lazy) is quoted from http://blog.sina.com.cn/s/blog_3cdfaea201008utf.html
- UPLOAD_ERR_OK Value: 0; No error occurred and the file was uploaded successfully.
- UPLOAD_ERR_INI_SIZE Value: 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 was uploaded.
- UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.
Note: This error message is the information uploaded in the first step, that is, when uploading to a temporary folder, not when moving or copying.
2. Upload related restrictions
2.1 Client restrictions
1 2 | <form action= "doAction2.php" method= "post" enctype= "multipart/form-data" >
<input type= "hidden" name= "MAX_FILE_SIZE" value= "101321" />
|
Copy after login
Please Select the file you want to upload:
1 2 3 | <input type= "file" name= "myFile" accept= "image/jpeg,image/gif,text/html" /><br/>
<input type= "submit" value= "上传" />
</form>
|
Copy after login
The input attributes are used here to limit the size and type of uploaded files, but my personal feeling is: , the html code is "visible"; second, it often doesn't work (I didn't find 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 the size and type, and then the method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | <?php
header('content-type:text/html;charset=utf-8');
$fileinfo = $_FILES [ "myFile" ];
$filename = $fileinfo [ "name" ];
$tmp_name = $fileinfo [ "tmp_name" ];
$size = $fileinfo [ "size" ];
$error = $fileinfo [ "error" ];
$type = $fileinfo [ "type" ];
$maxsize =10485760;
$allowExt = array ('jpeg','jpg','png','tif');
$ext = pathinfo ( $filename ,PATHINFO_EXTENSION);
$path = "uploads" ;
if (! file_exists ( $path )) {
mkdir ( $path ,0777,true);
chmod ( $path , 0777);
}
$uniName =md5(uniqid(microtime(true),true)). $ext ;
if ( $error ==0) {
if ( $size > $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 )) {
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | <?php
function uploadFile( $fileInfo , $path , $allowExt , $maxSize ){
$filename = $fileInfo [ "name" ];
$tmp_name = $fileInfo [ "tmp_name" ];
$size = $fileInfo [ "size" ];
$error = $fileInfo [ "error" ];
$type = $fileInfo [ "type" ];
$ext = pathinfo ( $filename ,PATHINFO_EXTENSION);
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 ( "上传文件过大!" );
}
if (!in_array( $ext , $allowExt )) {
exit ( "非法文件类型" );
}
if (! is_uploaded_file ( $tmp_name )) {
exit ( "上传方式有误,请使用post方式" );
}
if (! getimagesize ( $tmp_name )) {
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
1 2 3 4 5 6 7 8 | <?php
header('content-type:text/html;charset=utf-8');
$fileInfo = $_FILES [ "myFile" ];
$maxSize =10485760;
$allowExt = array ('jpeg','jpg','png','tif');
$path = "uploads" ;
include_once 'upFunc.php';
uploadFile( $fileInfo , $path , $allowExt , $maxSize );
|
Copy after login
3. Implementation of uploading multiple files
3.1 Use single file encapsulation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" >
<title>Insert title here</title>
</head>
<body>
<form action= "doAction5.php" method= "post" enctype= "multipart/form-data" >
请选择您要上传的文件:<input type= "file" name= "myFile1" /><br/>
请选择您要上传的文件:<input type= "file" name= "myFile2" /><br/>
请选择您要上传的文件:<input type= "file" name= "myFile3" /><br/>
请选择您要上传的文件:<input type= "file" name= "myFile4" /><br/>
<input type= "submit" value= "上传" />
</form>
</body>
</html>
<?php
header('content-type:text/html;charset=utf-8');
include_once 'upFunc.php';
foreach ( $_FILES as $fileInfo ){
$file []=uploadFile( $fileInfo );
}
|
Copy after login
The idea here is found in print_r($_FILES) and printed out Seeing 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
1 | function uploadFile( $fileInfo , $path = "uploads" , $allowExt = array ('jpeg','jpg','png','tif'), $maxSize =10485760){
|
Copy after login
This way, 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 immediately Stop, causing other pictures to be unable to be uploaded.
3.2 Upgraded version of packaging
Aims to implement packaging for uploading multiple or single files
First write a static file like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" >
<title>Insert title here</title>
</head>
<body>
<form action= "doAction5.php" method= "post" enctype= "multipart/form-data" >
请选择您要上传的文件:<input type= "file" name= "myFile[]" /><br/>
请选择您要上传的文件:<input type= "file" name= "myFile[]" /><br/>
请选择您要上传的文件:<input type= "file" name= "myFile[]" /><br/>
请选择您要上传的文件:<input type= "file" name= "myFile[]" /><br/>
<input type= "submit" value= "上传" />
</form>
</body>
</html>
|
Copy after login
Print $_FILES
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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
可以得到一个三维数组。
复杂是复杂了,但复杂的有规律,各项数值都在一起了,很方便我们取值!!
所以先得到文件信息,变成单文件处理那种信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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 ){
$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
然后之前的那种exit错误,就把exit改一下就好了,这里用res
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | function uploadFile( $fileInfo , $path ='./uploads', $flag =true, $maxSize =1048576, $allowExt = array ('jpeg','jpg','png','gif')){
$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'].'不是真实图片类型';
}
}
if (! is_uploaded_file ( $fileInfo ['tmp_name'])){
$res ['mes']= $fileInfo ['name'].'文件不是通过HTTP POST方式上传上来的';
}
if ( $res ) return $res ;
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
里面封装了两个小的
1 2 3 4 5 6 7 8 9 10 11 | function getExt( $filename ){
return strtolower ( pathinfo ( $filename ,PATHINFO_EXTENSION));
}
function getUniName(){
return md5(uniqid(microtime(true),true));
}
|
Copy after login
然后静态中,用multiple属性实现多个文件的输入;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" >
<title>Insert title here</title>
</head>
<body>
<form action= "doAction6.php" method= "POST" enctype= "multipart/form-data" >
请选择您要上传的文件:<input type= "file" name= "myFile[]" multiple='multiple' /><br/>
<input type= "submit" value= "上传" />
</form>
</body>
</html>
doAction6
<?php
header( "content-type:text/html;charset=utf-8" );
require_once 'upFunc2.php';
require_once 'common.func.php';
$files =getFiles();
foreach ( $files as $fileInfo ){
$res =uploadFile( $fileInfo );
echo $res ['mes'],'<br/>';
$uploadFiles []=@ $res ['dest'];
}
$uploadFiles = array_values ( array_filter ( $uploadFiles ));
|
Copy after login
这样子的几个文件,就实现比较强大的面向过程的上传文件的功能(学的叫一个心酸。。。);
四、面向对象的文件上传
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | <?php
class upload{
protected $fileName ;
protected $maxSize ;
protected $allowMime ;
protected $allowExt ;
protected $uploadPath ;
protected $imgFlag ;
protected $fileInfo ;
protected $error ;
protected $ext ;
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];
}
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;
}
}
protected function checkSize(){
if ( $this ->fileInfo['size']> $this ->maxSize){
$this ->error='上传文件过大';
return false;
}
return true;
}
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;
}
protected function checkMime(){
if (!in_array( $this ->fileInfo['type'], $this ->allowMime)){
$this ->error='不允许的文件类型';
return false;
}
return true;
}
protected function checkTrueImg(){
if ( $this ->imgFlag){
if (!@ getimagesize ( $this ->fileInfo['tmp_name'])){
$this ->error='不是真实图片';
return false;
}
return true;
}
}
protected function checkHTTPPost(){
if (! is_uploaded_file ( $this ->fileInfo['tmp_name'])){
$this ->error='文件不是通过HTTP POST方式上传上来的';
return false;
}
return true;
}
protected function showError(){
exit ('<span style= "color:red" >'. $this ->error.'</span>');
}
protected function checkUploadPath(){
if (! file_exists ( $this ->uploadPath)){
mkdir ( $this ->uploadPath,0777,true);
}
}
protected function getUniName(){
return md5(uniqid(microtime(true),true));
}
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();
}
}
}
<?php
header('content-type:text/html;charset=utf-8');
require_once 'upload. class .php';
$upload = new upload('myFile1','imooc');
$dest = $upload ->uploadFile();
echo $dest ;
|
Copy after login
四、下载
对于浏览器不识别的,可以直接下载,但对于能识别的,需要多一两步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns= "http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<a href= "1.rar" >下载1.rar</a>
<br />
<a href= "1.jpg" >下载1.jpg</a>
<br />
<a href= "doDownload.php?filename=1.jpg" >通过程序下载1.jpg</a>
<br />
<a href= "doDownload.php?filename=../upload/nv.jpg" >下载nv.jpg</a>
<?php
?>
</body>
</html>
<?php
$filename = $_GET ['filename'];
header('content-disposition:attachment;filename='. basename ( $filename ));
header('content-length:'. filesize ( $filename ));
readfile( $filename );
|
Copy after login
总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。
相关推荐:
PHP字符串定义方式及各自区别
php substr函数定义与用法汇总
php 三元运算符实例详细介绍
The above is the detailed content of How to implement file upload and download in PHP. For more information, please follow other related articles on the PHP Chinese website!