小編給大家分享一下PHP如何實現文件上傳下載,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
一、上傳原理與配置
1.1 原理
將客戶端文件上傳到服務器端,再將服務器端的文件(臨時文件)移動到指定目錄即可。
1.2 客戶端配置
所需:表單頁面(選擇上傳文件);
具體而言:發送方式為POST,添加enctype="multipart/form-data"屬性,兩者缺一不可(但是,優缺點并存,這里也限定了上傳的方式和上傳的文件之后的調用等方面,后面會說到
<!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>
先是表單頁面(請自動忽略前端問題。。。),關鍵就是form的屬性;另外就是input 中用到了type="file"這一點(體現到php的強大的拓展等等)。
然后是doAction.php
<?php
//$_FILES:文件上傳變量
//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_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;
}
}先把print_r($_FILES)這個信息看一下
Array
(
[myFile] => Array
(
[name] => 梁博_簡歷.doc
[type] => application/msword
[tmp_name] => D:\wamp\tmp\php1D78.tmp
[error] => 0
[size] => 75776
)
)所以得到的是個二維數組,該怎么用,都是基本的東西(其實我喜歡降維再用);
基本是一眼就懂的東西,不羅嗦,關鍵有兩個:tmp_name臨時文件名;error報錯信息(代號,后面可以利用);
然后這里看一下doAction后面一部分,利用報錯信息來反饋給用戶,需要說明的是為什么報錯,和報錯信息是什么都
1.3 關于報錯
--報錯原因
基本上都是超過或者不符合服務器關于上傳文件的配置,那么服務器端配置有哪些呢?
先考慮上傳我們用了什么?POST,upload
所以在php.ini中找這么幾項:
file_upload:On
upload_tmp_dir=——臨時文件保存目錄;
upload_max_filesize=2M
max_file_uploads=20——允許一次上傳的最大文件數量(注意和上面那個的區別,有沒有size,別亂想)
post_max_size=8M——post方式發送數據的最大值
其他相關配置
max_exectuion_time=-1——最大執行時間,避免程序不好占用服務器資源;
max_input_time=60
max_input_nesting_level=64——輸入嵌套深度;
memory_limit=128M——最大單線程的獨立內存使用量
總之都是有關資源的配置。
--錯誤號
UPLOAD_ERR_OK 值:0; 沒有錯誤發生,文件上傳成功。UPLOAD_ERR_INI_SIZE 值:1; 上傳的文件超過了 php.ini 中 upload_max_filesize 選項限制的值。UPLOAD_ERR_FORM_SIZE 值:2; 上傳文件的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項指定的值。UPLOAD_ERR_PARTIAL 值:3; 文件只有部分被上傳。UPLOAD_ERR_NO_FILE 值:4; 沒有文件被上傳。
注意:這個錯誤信息是第一步上傳的信息,也就是上傳到臨時文件夾的情況,而不是move或者copy的情況。
二、上傳相關限制
2.1 客戶端限制
<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>
這里用input的屬性對上傳文件的大小和類型進行了限制,但是個人感覺:一,html代碼是“可見的”;二,常不起作用(沒找到原因,但因為第一個我也想放棄它,知道就好。
2.2 服務器端限制
主要限制大小和類型,再有就是方式。
<?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;//10M,10*1024*1024
$allowExt=array('jpeg','jpg','png','gif');//允許上傳的文件類型(拓展名
$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 封裝
函數
<?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)) {//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;
}調用
<?php
header('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);三、多文件的上傳實現
3.1 利用單文件封裝
<!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('content-type:text/html;charset=utf-8');
include_once 'upFunc.php';
foreach ($_FILES as $fileInfo){
$file[]=uploadFile($fileInfo);
}這里的思路,從print_r($_FILES)中去找,打印出來看到是個二維數組,很簡單,遍歷去用就好了!
上面那個function的定義改一下,給定一些默認值
function uploadFile($fileInfo,$path="uploads",$allowExt=array('jpeg','jpg','png','tif'),$maxSize=10485760){這樣子,簡單是簡單,但遇到一些問題。
正常的上傳4個圖片是沒問題,但要是中間激活了函數中的exit,就會立即停止,導致其他圖片也無法上傳。
3.2升級版封裝
旨在實現針對多個或單個文件上傳的封裝
首先這樣子寫個靜態文件
<!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>
打印一下$_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
)
)
)可以得到一個三維數組。
復雜是復雜了,但復雜的有規律,各項數值都在一起了,很方便我們取值??!
所以先得到文件信息,變成單文件處理那種信息
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;
}然后之前的那種exit錯誤,就把exit改一下就好了,這里用res
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;
}
}里面封裝兩個小的
function getExt($filename){
return strtolower(pathinfo($filename,PATHINFO_EXTENSION));
}
/**
* 產生唯一字符串
* @return string
*/
function getUniName(){
return md5(uniqid(microtime(true),true));
}然后在靜態中,使用multiple屬性實現多個文件的輸入
<!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
<?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'],'<br/>';
$uploadFiles[]=@$res['dest'];
}
$uploadFiles=array_values(array_filter($uploadFiles));
//print_r($uploadFiles);四、面向對象的文件上傳
<?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='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];
}
/**
* 檢測上傳文件是否出錯
* @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('<span style="color:red">'.$this->error.'</span>');
}
/**
* 檢測目錄不存在則創建
*/
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();
}
}
}<?php
header('content-type:text/html;charset=utf-8');
require_once 'upload.class.php';
$upload=new upload('myFile1','imooc');
$dest=$upload->uploadFile();
echo $dest;五、下載
<!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);總結:
<form action="doAction.php" method="post" enctype="multipart/form-data">
<input type="file" name="myFile" /><br/>
二維數組的降維處理;
$_FILES變量
move_upload_file();copy();
tmp_name臨時文件;
拓展名的提??;
真實圖片的驗證;
唯一文件名的生成;
函數封裝以及調用;
利用單個文件函數實現多文件上傳;
小功能的封裝;
多文件的遍歷;
面向對象的開發過程;
下載;
看完了這篇文章,相信你對PHP如何實現文件上傳下載有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。