php 三種檔案下載的實現
阿新 • • 發佈:2019-01-10
1、直接新增檔案連結
<button>
<a href = "http://localhost/down.zip">
下載檔案
</button>
點選該按鈕下載:
2、傳遞引數查詢並跳轉到下載連結
傳遞引數:
<button>
<a href = "http://localhost?f='down'">
下載檔案
</button>
查詢檔案並挑戰到下載連結:
<?php
$down = $_GET['f']; //獲取檔案引數
$filename = $down .'.zip'; //獲取檔名稱
$dir ="down/"; //相對於網站根目錄的下載目錄路徑
$down_host = $_SERVER['HTTP_HOST'].'/'; //當前域名
//判斷如果檔案存在,則跳轉到下載路徑
if(file_exists(__DIR__.'/'.$dir.$filename)){
header('location:http://'.$down_host.$dir.$filename);
}else{
header('HTTP/1.1 404 Not Found');
}
結果:
- 檔案存在
- 檔案不存在
3、head() 和 fread()函式把檔案直接輸出到瀏覽器
<?php
$file_name = "down";
$file_name = "down.zip"; //下載檔名
$file_dir = "./down/"; //下載檔案存放目錄
//檢查檔案是否存在
if (! file_exists ( $file_dir . $file_name )) {
header('HTTP/1.1 404 NOT FOUND');
} else {
//以只讀和二進位制模式開啟檔案
$file = fopen ( $file_dir . $file_name, "rb" );
//告訴瀏覽器這是一個檔案流格式的檔案
Header ( "Content-type: application/octet-stream" );
//請求範圍的度量單位
Header ( "Accept-Ranges: bytes" );
//Content-Length是指定包含於請求或響應中資料的位元組長度
Header ( "Accept-Length: " . filesize ( $file_dir . $file_name ) );
//用來告訴瀏覽器,檔案是可以當做附件被下載,下載後的檔名稱為$file_name該變數的值。
Header ( "Content-Disposition: attachment; filename=" . $file_name );
//讀取檔案內容並直接輸出到瀏覽器
echo fread ( $file, filesize ( $file_dir . $file_name ) );
fclose ( $file );
exit ();
}
結果:和第二個一樣
總結:第一個和第二個操作比較簡單,但是容易暴露檔案的真實地址,安全性不高,第三種能夠較好的把檔案的真實地址隱藏起來