首頁  >  文章  >  後端開發  >  php下載檔案的方法【總結】

php下載檔案的方法【總結】

藏色散人
藏色散人原創
2020-08-18 10:49:038747瀏覽

php下載檔案的方法:1、從「$_GET['file']」得到檔案路徑;2、設定header資訊;3、使用「file_get_contents()」和「file()」方法; 4.透過「readfile」和「fopen」方法。

php下載檔案的方法【總結】

推薦:《PHP影片教學》 

PHP下載檔案的方式

1. 得到檔案路徑

從$_GET['file']得到檔案路徑

$path_parts = pathinfo($_GET['file']);
$file_name  = $path_parts['basename'];
$file_path  = '/mysecretpath/' . $file_name;

務必使用上面這個方法得到路徑,不能簡單的字串拼接得到路徑

$mypath = '/mysecretpath/' . $_GET['file'];

如果輸入的是../../,就可以存取任何路徑

2. 設定header資訊

header('Content-Description: File Transfer'); //描述页面返回的结果
header('Content-Type: application/octet-stream'); //返回内容的类型,此处只知道是二进制流。具体返回类型可参考http://tool.oschina.net/commons
header('Content-Disposition: attachment; filename='.basename($file));//可以让浏览器弹出下载窗口
header('Content-Transfer-Encoding: binary');//内容编码方式,直接二进制,不要gzip压缩
header('Expires: 0');//过期时间
header('Cache-Control: must-revalidate');//缓存策略,强制页面不缓存,作用与no-cache相同,但更严格,强制意味更明显
header('Pragma: public');
header('Content-Length: ' . filesize($file));//文件大小,在文件超过2G的时候,filesize()返回的结果可能不正确

3. 輸出檔案之file_get_contents()方法

file_get_contents()把檔案內容讀取到字串,也就是要把檔案讀到記憶體中,再輸出內容

$str = file_get_contents($file);
echo $str;

這種方式,只要檔案稍微一大,就會超過記憶體限制

4. 輸出檔之file()方法

與file_get_contents()差不多,只不過是file()會把內容按行讀取到陣列中,也是需要佔用記憶體

$f = file($file);
while(list($line, $cnt) = each($f)) {
   echo $cnt;
}

檔案大的時候也會超出記憶體限制

5. 輸出檔案之readfile()方法

readfile()方法:讀入一個檔案並寫入到輸出緩衝

這種方式可以直接輸出到緩衝,不會整個檔案佔用記憶體

前提要先清空緩衝,先要讓使用者看到下載檔案的對話方塊

while (ob_get_level()) ob_end_clean();
//设置完header以后
ob_clean();
flush();  //清空缓冲区
readfile($file);

這種方法可以輸出大文件,讀取單一文件不會超出記憶體限制,但下面的情況除外。

readfile()在多人讀取檔案的時候同樣會造成PHP記憶體耗盡:http://stackoverflow.com/questions/6627952/why-does-readfile-exhaust-php- memory

PHP has to read the file and it writes to the output buffer. So, for 300Mb file, no matter what the implementation you wrote (by many small segments, or by 1 big chunk) PHP has to read through 300Mb of file eventually.

If multiple user has to download the file, there will be a problem. (In one server, hosting providers will limit memory given to each hosting user. With suffer, liory is not going to be a good idea. )

I think using the direct link to download a file is a much better approach for big files.

大意:PHP需要讀取檔案,再輸出到緩衝。對於一個300M的文件,PHP最終還是要讀300M記憶體。因此在多個用戶同時下載的時候,緩衝也會耗盡記憶體。 (不對還請指正)

例如100個使用者在下載,就需要100*buffer_size大小的記憶體

6. 輸出檔案之fopen()方法

set_time_limit(0);
$file = @fopen($file_path,"rb");
while(!feof($file))
{
    print(@fread($file, 1024*8));
    ob_flush();
    flush();
}

fopen ()可以讀入大文件,每次可以指定讀取一部分的內容。在操作大檔案的時候也很有用

7. 總結

利用PHP下載檔案時,應該要專注於場景。如果本身只是幾個小檔案下載,那麼使用PHP下載比較好;但是如果PHP要承受大量下載請求,這時下載檔案就不該交給PHP做。

對於Apache,有mod_xsendfile可以幫助完成下載任務,更簡單也更快速

以上是php下載檔案的方法【總結】的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn