復制代碼 代碼如下:
 /*======================================================
  $FileName 為文件名稱,必傳
  $FilePath 為文件路徑.選填,可以為相對路徑或者絕對路徑
      路徑只能由英文跟數據組成,不能帶有中文
 ======================================================*/
<?php 
 header("Content-type: text/html;charset=utf-8");
 if(strlen($FileName)<=3){echo "下載失敗:你所以下載的文件信息有誤";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);
 }
?>
新聞熱點
疑難解答