PHP realizes the upload principle and implementation of file upload and download
Upload principle
Upload the client files to the server, and then move the server-side files (temporary files) to the specified directory.
By learning file upload, you will see the essence of file upload through the phenomenon of use!
Upload implementation
1. Client configuration
Select the file upload page (form page)
The following two are indispensable:
Sending method is POST
Add enctype="multipart/form-data" attribute
index.php code is as follows:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="format-detection" content="telephone=no" /> <title>文件上传</title> <meta charset="utf-8" /> </head> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> 请选择您要上传的文件:<br/> <input type="file" name="myFile" /><br/> <input type="submit" value="上传"/> </form> </body> </html>
Note: The key is the attribute of form; the other is that type="file" is used in input
##2. Upload processing page
The upload program processing flow chart is as follows:
upload.php code is as follows:
<?php header("Content-type:text/html;charset=utf-8"); //文件上传处理程序 //$_FILES:文件上传变量 /*echo "<pre>"; var_dump($_FILES); exit; echo "</pre>";*/ $filename=$_FILES['myFile']['name']; $type=$_FILES['myFile']['type']; $tmp_name=$_FILES['myFile']['tmp_name']; $size=$_FILES['myFile']['size']; $error=$_FILES['myFile']['error']; //将服务器上的临时文件移动到指定位置 //方法一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; } }After clicking upload, the following appears:
Note: You need to create a new uploads folder in the same directory as upload.php to store uploaded images, otherwise an error will be reported