php如何实现下载文件
生活随笔
收集整理的這篇文章主要介紹了
php如何实现下载文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
php實現下載文件的方法:1、直接添加文件鏈接方法;2、傳遞參數查找并跳轉到下載鏈接方法;3、使用函數【head()】和【fread()】函數把文件直接輸出到瀏覽器方法。
php實現下載文件的方法:
1、直接添加文件鏈接
<button>
<a href = "http://localhost/down.zip">
下載文件
</button>
點擊該按鈕下載:
相關學習推薦:php編程(視頻)
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 ();
}
結果:和第二個一樣
總結:第一個和第二個操作比較簡單,但是容易暴露文件的真實地址,安全性不高,第三種能夠較好的把文件的真實地址隱藏起來
相關推薦:編程視頻課程
總結
以上是生活随笔為你收集整理的php如何实现下载文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php停止命令是什么
- 下一篇: PHP怎样实现网址伪静态