關於php使用header實現下載功能
test1.php關鍵代碼,這裡省略連結資料庫相關代碼,只有從資料庫中讀出相關代碼
$sql_select = "SELECT * FROM `file_information` order by id DESC";
$sql_mysql = mysql_query($sql_select,$connected);
?>
| ID |
縮圖 |
簡介 |
路徑 |
長傳時間 |
操作 |
while($sql_fetch = mysql_fetch_array($sql_mysql)){?>
|
" width="80" heihgt="80"/> |
|
|
|
">下載 |
}?>
test2.php代碼:(由於header("Content-Type: text/html;charset=UTF-8")給予了類型,所以其他html代碼全部刪除了,並且沒有將test2.php中的php代碼寫在test1.php中,因為test1.php有有輸出,會影響header()設定類型
header("Content-Type: text/html;charset=UTF-8");
if(!empty($_GET['download_id']))
{
$download_id = $_GET['download_id'];
$download_id = explode("@@@",$download_id);
$download_path = $download_id[1];
if(!is_null($download_path))
{
$filename = basename($download_path);//擷取檔案名稱
$download_file = fopen($download_path,"r");
if($download_file)
{
header("Content-Type:application/octet-stream");
header("Accept-Ranges:bytes");
header("Accept-Length:".filesize($download_path));
header("Content-Disposition: attachment; filename=".$filename);
echo fread($download_file,filesize($download_path));
fclose($download_file);
exit;
}
else
{
echo "The file must be not exist";
}
}
}
?>
這麼做其實是可以的,而且下載功能也可以執行,經過測試,在IE9,chrome,firefox上面都可以運行,jpg檔案,png檔案,txt檔案,swf檔案都可以下載並查看,但是基於chrome核心的360極速瀏覽器確出現問題,當圖片是png格式時,可以下載並開啟,當圖片是jpg格式時,可以下載,大小卻為0B,打不開圖片,這應該是瀏覽器問題吧?不過chrome都可以為什麼它不可以??求好銀不思賜教why,thank you!(ps:360極速瀏覽器的極速模式,相容模式,IE9模式均不可以下載jpg格式圖片)
------解決方案--------------------
if(file_exists($download_file)){
//
}