網站有從遠程服務器通過http下載文件的需求,于是寫了個提供文件下載的腳本,下面我們來看看用PHP如何實現文件下載功能的.
偶爾用用PHP寫點這種很小很小的Web程序,還是蠻簡單方便的.
PHP實現文件下載功能的代碼如下:
- <?php
- $base_dir = "/usr/share/nginx/html/";
- $myfile = $base_dir . $_GET["file"];
- //echo $myfile;
- //開源軟件:Vevb.com
- if( ! file_exists($myfile) ) {
- echo "file: " . $myfile . " doesn't exist.";
- } elseif ( is_dir($myfile) ) {
- echo "file: " . $myfile . " is a directory.";
- } else {
- header("Content-type: application/octet-stream");
- header('Content-Disposition: attachment; filename="' . basename($myfile) . '"');
- header("Content-Length: ". filesize($myfile));
- readfile($myfile);
- }
- ?>
github:https://github.com/smilejay/other-code/blob/master/php/download.php
另外,一個牛人分析一下使用apache/nginx的一些模塊讓php實現問下下載更加的高效:
http://www.laruence.com/2012/05/02/2613.html
新聞熱點
疑難解答