本篇文章給大家詳細介紹php 三種文件下載的實現有一定的參考價值,有需要的朋友可以參考一下,希望對大家有所幫助。
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 (); }
結果:和第二個一樣
總結:第一個和第二個操作比較簡單,但是容易暴露文件的真實地址,安全性不高,第三種能夠較好的把文件的真實地址隱藏起來
推薦學習:php視頻教程