php實現(xiàn)下載文件的方法:1、直接添加文件鏈接方法;2、傳遞參數(shù)查找并跳轉(zhuǎn)到下載鏈接方法;3、使用函數(shù)【head()】和【fread()】函數(shù)把文件直接輸出到瀏覽器方法。
php實現(xiàn)下載文件的方法:
1、直接添加文件鏈接
<button> <a href = "http://localhost/down.zip"> 下載文件</button>點擊該按鈕下載:
相關(guān)學(xué)習(xí)推薦:php編程(視頻)
2、傳遞參數(shù)查找并跳轉(zhuǎn)到下載鏈接
傳遞參數(shù):
<button> <a href = "http://localhost?f='down'"> 下載文件</button>查找文件并挑戰(zhàn)到下載鏈接:
<?php$down = $_get['f']; //獲取文件參數(shù)$filename = $down.'.zip'; //獲取文件名稱$dir ="down/"; //相對于網(wǎng)站根目錄的下載目錄路徑$down_host = $_server['http_host'].'/'; //當(dāng)前域名//判斷如果文件存在,則跳轉(zhuǎn)到下載路徑if(file_exists(__dir__.'/'.$dir.$filename)){ header('location:http://'.$down_host.$dir.$filename);}else{ header('http/1.1 404 not found');}結(jié)果:
文件存在
文件不存在
3、head() 和 fread()函數(shù)把文件直接輸出到瀏覽器
<?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是指定包含于請求或響應(yīng)中數(shù)據(jù)的字節(jié)長度 header ( "accept-length: " . filesize ( $file_dir . $file_name ) ); //用來告訴瀏覽器,文件是可以當(dāng)做附件被下載,下載后的文件名稱為$file_name該變量的值。 header ( "content-disposition: attachment; filename=" . $file_name ); //讀取文件內(nèi)容并直接輸出到瀏覽器 echo fread ( $file, filesize ( $file_dir . $file_name ) ); fclose ( $file ); exit (); }結(jié)果:和第二個一樣
總結(jié):第一個和第二個操作比較簡單,但是容易暴露文件的真實地址,安全性不高,第三種能夠較好的把文件的真實地址隱藏起來
相關(guān)推薦:編程視頻課程