這個文件下載實例做得非常的詳細他是結合header函數與while fread函數把文件分斷讀出來然后再發送到客戶端了,算得上一個標準的文件下載實例。
一個PHP文件下載的小實例
- /*======================================================
- $FileName 為文件名稱,必傳
- $FilePath 為文件路徑.選填,可以為相對路徑或者絕對路徑
- 路徑只能由英文跟數據組成,不能帶有中文
- 如有問題 歡迎聯系博主指出
- ======================================================*/
- 代碼如下 復制代碼
- <?php
- header("Content-type: text/html;charset=utf-8");
- if(strlen($FileName)<=3){echo "下載失?。耗闼韵螺d的文件信息有誤";return;}
- $FileName=iconv("utf-8","gb2312",$FileName);//進行文件名格式轉換,以防中文亂碼
- //開始判斷路徑
- if(!is_null($FilePath)&&strlen($FilePath)>1){
- if(substr($FilePath,0,1)=='/'){//判斷是否為絕對路徑
- $FilePath=$_SERVER['DOCUMENT_ROOT'].$FilePath;
- }
- if(substr($FilePath,-1)!="/"){//檢查最后是否為 / 結尾
- $FilePath=$FilePath.'/';
- }
- if(is_numeric(strpos($FilePath,":/"))){//檢查是否為絕對路徑
- $FilePath=str_replace("/","/",$FilePath);
- }
- }elseif(strlen($FilePath)==1&&$FilePath!="/"){
- $FilePath=$FilePath."/";
- }else{
- $FilePath="";
- }
- if(!file_exists($FilePath.$FileName)){
- echo"下載失敗:所要下載的文件未找到";return;
- }
- /*================================================
- 發送下載相關的頭部信息
- =================================================*/
- header("Content-type: application/octet-stream");
- header("Accept-Ranges: bytes");//按照字節大小返回
- header("Accept-Length: $FileSize");//返回文件大小
- header("Content-Disposition: attachment; filename=".$FileName);//這里客戶端的彈出對話框,對應的文件名
- /*================================================
- 開始下載相關
- =================================================*/
- $FileSize=filesize($FilePath.$FileName);
- $File=fopen($FilePath.$FileName,"r");//打開文件
- $FileBuff=512;
- while($FileSize>=0){
- $FileSize-=$FileBuff;
- echo fread($File,$FileBuff);
- }
- fclose($File);
- }
- ?>
總結:本下載實例并且支持中文文名了,在文件開頭就進行了uft8編碼轉換了.
新聞熱點
疑難解答