search
HomeBackend DevelopmentPHP TutorialDetailed explanation of file upload and download examples using PHP

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 is POST, add enctype="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

<!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="doAction.php" method="post" enctype="multipart/form-data">
请选择您要上传的文件:
<input type="file" name="myFile" /><br/>
<input type="submit" value="上传"/>
</form>
<?php

?>
</body>
</html>

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

<?php
//$_FILES:文件上传变量
//print_r($_FILES);
$filename=$_FILES[&#39;myFile&#39;][&#39;name&#39;];
$type=$_FILES[&#39;myFile&#39;][&#39;type&#39;];
$tmp_name=$_FILES[&#39;myFile&#39;][&#39;tmp_name&#39;];
$size=$_FILES[&#39;myFile&#39;][&#39;size&#39;];
$error=$_FILES[&#39;myFile&#39;][&#39;error&#39;];

//将服务器上的临时文件移动到指定位置
//方法一move_upload_file($tmp_name,$destination)
//move_uploaded_file($tmp_name, "uploads/".$filename);//文件夹应提前建立好,不然报错
//方法二copy($src,$des)
//以上两个函数都是成功返回真,否则返回false
//copy($tmp_name, "copies/".$filename);
//注意,不能两个方法都对临时文件进行操作,临时文件似乎操作完就没了,我们试试反过来
copy($tmp_name, "copies/".$filename);
move_uploaded_file($tmp_name, "uploads/".$filename);
//能够实现,说明move那个函数基本上相当于剪切;copy就是copy,临时文件还在

//另外,错误信息也是不一样的,遇到错误可以查看或者直接报告给用户
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;
    }
}

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
        )

)

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_name Temporary 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_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 is 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, uploaded to a temporary folder, not the case of move or copy.

2. Upload related restrictions

2.1 Client restrictions

<form action="doAction2.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="101321" />
请选择您要上传的文件:
<input type="file" name="myFile" accept="image/jpeg,image/gif,text/html"/><br/>
<input type="submit" value="上传"/>
</form>

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.

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
//接受文件,临时文件信息
$fileinfo=$_FILES["myFile"];//降维操作
$filename=$fileinfo["name"];
$tmp_name=$fileinfo["tmp_name"];
$size=$fileinfo["size"];
$error=$fileinfo["error"];
$type=$fileinfo["type"];

//服务器端设定限制
$maxsize=10485760;//10M,10*1024*1024
$allowExt=array(&#39;jpeg&#39;,&#39;jpg&#39;,&#39;png&#39;,&#39;gif&#39;);//允许上传的文件类型(拓展名
$ext=pathinfo($filename,PATHINFO_EXTENSION);//提取上传文件的拓展名

//目的信息
$path="uploads";
if (!file_exists($path)) {   //当目录不存在,就创建目录
    mkdir($path,0777,true);
    chmod($path, 0777);
}
//$destination=$path."/".$filename;
//得到唯一的文件名!防止因为文件名相同而产生覆盖
$uniName=md5(uniqid(microtime(true),true)).$ext;//md5加密,uniqid产生唯一id,microtime做前缀


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

2.3 Encapsulation

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"];

//服务器端设定限制

$ext=pathinfo($filename,PATHINFO_EXTENSION);

//目的信息
if (!file_exists($path)) {   
    mkdir($path,0777,true);
    chmod($path, 0777);
}
$uniName=md5(uniqid(microtime(true),true)).&#39;.&#39;.$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)) {//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;
}

Call

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
$fileInfo=$_FILES["myFile"];
$maxSize=10485760;//10M,10*1024*1024
$allowExt=array(&#39;jpeg&#39;,&#39;jpg&#39;,&#39;png&#39;,&#39;tif&#39;);
$path="uploads";
include_once &#39;upFunc.php&#39;;
uploadFile($fileInfo, $path, $allowExt, $maxSize);

3. Implementation of uploading multiple files

3.1 Use single file encapsulation

<!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
//print_r($_FILES);
header(&#39;content-type:text/html;charset=utf-8&#39;);
include_once &#39;upFunc.php&#39;;
foreach ($_FILES as $fileInfo){
    $file[]=uploadFile($fileInfo);
}

The idea here is from print_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(&#39;jpeg&#39;,&#39;jpg&#39;,&#39;png&#39;,&#39;tif&#39;),$maxSize=10485760){

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

<!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>

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
                )

        )

)

.

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[&#39;name&#39;])){  //单文件判定
            $files[$i]=$file;
            $i++;
        }elseif(is_array($file[&#39;name&#39;])){
            foreach($file[&#39;name&#39;] as $key=>$val){  //我的天,这个$key用的diao
                $files[$i][&#39;name&#39;]=$file[&#39;name&#39;][$key];
                $files[$i][&#39;type&#39;]=$file[&#39;type&#39;][$key];
                $files[$i][&#39;tmp_name&#39;]=$file[&#39;tmp_name&#39;][$key];
                $files[$i][&#39;error&#39;]=$file[&#39;error&#39;][$key];
                $files[$i][&#39;size&#39;]=$file[&#39;size&#39;][$key];
                $i++;
            }
        }
    }
    return $files;
    
}

Then if there is an exit error like before, just change the exit. Use res## here.
#

function uploadFile($fileInfo,$path=&#39;./uploads&#39;,$flag=true,$maxSize=1048576,$allowExt=array(&#39;jpeg&#39;,&#39;jpg&#39;,&#39;png&#39;,&#39;gif&#39;)){
    //$flag=true;
    //$allowExt=array(&#39;jpeg&#39;,&#39;jpg&#39;,&#39;gif&#39;,&#39;png&#39;);
    //$maxSize=1048576;//1M
    //判断错误号
    $res=array();
    if($fileInfo[&#39;error&#39;]===UPLOAD_ERR_OK){
        //检测上传得到小
        if($fileInfo[&#39;size&#39;]>$maxSize){
            $res[&#39;mes&#39;]=$fileInfo[&#39;name&#39;].&#39;上传文件过大&#39;;
        }
        $ext=getExt($fileInfo[&#39;name&#39;]);
        //检测上传文件的文件类型
        if(!in_array($ext,$allowExt)){
            $res[&#39;mes&#39;]=$fileInfo[&#39;name&#39;].&#39;非法文件类型&#39;;
        }
        //检测是否是真实的图片类型
        if($flag){
            if(!getimagesize($fileInfo[&#39;tmp_name&#39;])){
                $res[&#39;mes&#39;]=$fileInfo[&#39;name&#39;].&#39;不是真实图片类型&#39;;
            }
        }
        //检测文件是否是通过HTTP POST上传上来的
        if(!is_uploaded_file($fileInfo[&#39;tmp_name&#39;])){
            $res[&#39;mes&#39;]=$fileInfo[&#39;name&#39;].&#39;文件不是通过HTTP POST方式上传上来的&#39;;
        }
        if($res) return $res;
        //$path=&#39;./uploads&#39;;
        if(!file_exists($path)){
            mkdir($path,0777,true);
            chmod($path,0777);
        }
        $uniName=getUniName();
        $destination=$path.&#39;/&#39;.$uniName.&#39;.&#39;.$ext;
        if(!move_uploaded_file($fileInfo[&#39;tmp_name&#39;],$destination)){
            $res[&#39;mes&#39;]=$fileInfo[&#39;name&#39;].&#39;文件移动失败&#39;;
        }
        $res[&#39;mes&#39;]=$fileInfo[&#39;name&#39;].&#39;上传成功&#39;;
        $res[&#39;dest&#39;]=$destination;
        return $res;
        
    }else{
        //匹配错误信息
        switch ($fileInfo [&#39;error&#39;]) {
            case 1 :
                $res[&#39;mes&#39;] = &#39;上传文件超过了PHP配置文件中upload_max_filesize选项的值&#39;;
                break;
            case 2 :
                $res[&#39;mes&#39;] = &#39;超过了表单MAX_FILE_SIZE限制的大小&#39;;
                break;
            case 3 :
                $res[&#39;mes&#39;] = &#39;文件部分被上传&#39;;
                break;
            case 4 :
                $res[&#39;mes&#39;] = &#39;没有选择上传文件&#39;;
                break;
            case 6 :
                $res[&#39;mes&#39;] = &#39;没有找到临时目录&#39;;
                break;
            case 7 :
            case 8 :
                $res[&#39;mes&#39;] = &#39;系统错误&#39;;
                break;
        }
        return $res;
    }
}

It encapsulates two small ones

function getExt($filename){
    return strtolower(pathinfo($filename,PATHINFO_EXTENSION));
}

/**
 * 产生唯一字符串
 * @return string
 */
function getUniName(){
    return md5(uniqid(microtime(true),true));
}

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


<!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=&#39;multiple&#39; /><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>

doAction6.php


<?php 
//print_r($_FILES);
header("content-type:text/html;charset=utf-8");
require_once &#39;upFunc2.php&#39;;
require_once &#39;common.func.php&#39;;
$files=getFiles();
// print_r($files);
foreach($files as $fileInfo){
    $res=uploadFile($fileInfo);
    echo $res[&#39;mes&#39;],&#39;<br/>&#39;;
    $uploadFiles[]=@$res[&#39;dest&#39;];
}
$uploadFiles=array_values(array_filter($uploadFiles));
//print_r($uploadFiles);

4. 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=&#39;myFile&#39;,$uploadPath=&#39;./uploads&#39;,$imgFlag=true,$maxSize=5242880,$allowExt=array(&#39;jpeg&#39;,&#39;jpg&#39;,&#39;png&#39;,&#39;gif&#39;),$allowMime=array(&#39;image/jpeg&#39;,&#39;image/png&#39;,&#39;image/gif&#39;)){
        $this->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[&#39;error&#39;]>0){
                switch($this->fileInfo[&#39;error&#39;]){
                    case 1:
                        $this->error=&#39;超过了PHP配置文件中upload_max_filesize选项的值&#39;;
                        break;
                    case 2:
                        $this->error=&#39;超过了表单中MAX_FILE_SIZE设置的值&#39;;
                        break;
                    case 3:
                        $this->error=&#39;文件部分被上传&#39;;
                        break;
                    case 4:
                        $this->error=&#39;没有选择上传文件&#39;;
                        break;
                    case 6:
                        $this->error=&#39;没有找到临时目录&#39;;
                        break;
                    case 7:
                        $this->error=&#39;文件不可写&#39;;
                        break;
                    case 8:
                        $this->error=&#39;由于PHP的扩展程序中断文件上传&#39;;
                        break;
                        
                }
                return false;
            }else{
                return true;
            }
        }else{
            $this->error=&#39;文件上传出错&#39;;
            return false;
        }
    }
    /**
     * 检测上传文件的大小
     * @return boolean
     */
    protected function checkSize(){
        if($this->fileInfo[&#39;size&#39;]>$this->maxSize){
            $this->error=&#39;上传文件过大&#39;;
            return false;
        }
        return true;
    }
    /**
     * 检测扩展名
     * @return boolean
     */
    protected function checkExt(){
        $this->ext=strtolower(pathinfo($this->fileInfo[&#39;name&#39;],PATHINFO_EXTENSION));
        if(!in_array($this->ext,$this->allowExt)){
            $this->error=&#39;不允许的扩展名&#39;;
            return false;
        }
        return true;
    }
    /**
     * 检测文件的类型
     * @return boolean
     */
    protected function checkMime(){
        if(!in_array($this->fileInfo[&#39;type&#39;],$this->allowMime)){
            $this->error=&#39;不允许的文件类型&#39;;
            return false;
        }
        return true;
    }
    /**
     * 检测是否是真实图片
     * @return boolean
     */
    protected function checkTrueImg(){
        if($this->imgFlag){
            if(!@getimagesize($this->fileInfo[&#39;tmp_name&#39;])){
                $this->error=&#39;不是真实图片&#39;;
                return false;
            }
            return true;
        }
    }
    /**
     * 检测是否通过HTTP POST方式上传上来的
     * @return boolean
     */
    protected function checkHTTPPost(){
        if(!is_uploaded_file($this->fileInfo[&#39;tmp_name&#39;])){
            $this->error=&#39;文件不是通过HTTP POST方式上传上来的&#39;;
            return false;
        }
        return true;
    }
    /**
     *显示错误 
     */
    protected function showError(){
        exit(&#39;<span style="color:red">&#39;.$this->error.&#39;</span>&#39;);
    }
    /**
     * 检测目录不存在则创建
     */
    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.&#39;/&#39;.$this->uniName.&#39;.&#39;.$this->ext;
            if(@move_uploaded_file($this->fileInfo[&#39;tmp_name&#39;], $this->destination)){
                return  $this->destination;
            }else{
                $this->error=&#39;文件移动失败&#39;;
                $this->showError();
            }
        }else{
            $this->showError();
        }
    }
}
<?php 
header(&#39;content-type:text/html;charset=utf-8&#39;);
require_once &#39;upload.class.php&#39;;
$upload=new upload(&#39;myFile1&#39;,&#39;imooc&#39;);
$dest=$upload->uploadFile();
echo $dest;

5. Download

<!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[&#39;filename&#39;];
header(&#39;content-disposition:attachment;
filename=&#39;.basename($filename));
header(&#39;content-length:&#39;.filesize($filename));
readfile($filename);

总结:


<input type="file" name="myFile"><br>

 二维数组的降维处理;

$_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!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function