[PHP] header下載檔案 搭配資料庫

剛剛在 ECstart 看到有人詢問 header檔案下載錯誤 發現網站義工有回答到這個function,所以就紀錄下來了
function dl_file($file){

   //First, see if the file exists
   if (!is_file($file)) { die("404 File not found!"); }

   //Gather relevent info about file
   $len = filesize($file);
   $filename = basename($file);
   $file_extension = strtolower(substr(strrchr($filename,"."),1));

   //This will set the Content-Type to the appropriate setting for the file
  switch( $file_extension ) {
     case "pdf": $ctype="application/pdf"; break;
     case "exe": $ctype="application/octet-stream"; break;
     case "zip": $ctype="application/zip"; break;
     case "doc": $ctype="application/msword"; break;
     case "xls": $ctype="application/vnd.ms-excel"; break;
     case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
     case "gif": $ctype="image/gif"; break;
     case "png": $ctype="image/png"; break;
     case "jpeg":
     case "jpg": $ctype="image/jpg"; break;
     case "mp3": $ctype="audio/mpeg"; break;
     case "wav": $ctype="audio/x-wav"; break;
     case "mpeg":
     case "mpg":
     case "mpe": $ctype="video/mpeg"; break;
     case "mov": $ctype="video/quicktime"; break;
     case "avi": $ctype="video/x-msvideo"; break;

     //The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
     case "php":
     case "htm":
     case "html":
     case "txt": die("Cannot be used for ". $file_extension ." files!"); break;

     default: $ctype="application/force-download";
   }

   //Begin writing headers
   header("Pragma: public");
   header("Expires: 0");
   header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
   header("Cache-Control: public");
   header("Content-Description: File Transfer");
   
   //Use the switch-generated Content-Type
   header("Content-Type: $ctype");

   //Force the download
   $header="Content-Disposition: attachment; filename=".$filename.";";
   header($header );
   header("Content-Transfer-Encoding: binary");
   header("Content-Length: ".$len);
   @readfile($file);
   exit;
}
  • windix

    你好,提醒一下,这个函数要小心使用,要注意检查入口参数$file是否是合法的,否则访客可通过构造特殊的字串来取得未经许可的文件。
    例如用户要下载的文件abc.pdf放置于 /var/www/htdocs/myweb.com/download/
    而用户使用通过构造诸如 ../../../../../etc/passwd 这样的字串,理论上来说,可以读出系统中任何文件的内容。

  • 恩 感謝樓上提醒,不過我的構想是搭配資料庫,之後去資料庫撈要下載的檔案,在傳到,dl_file($file) 這個函數裡面,這樣就不會有上面您說的問題了

  • Pingback: [心得]2008()

  • Pingback: [PHP]好用的上傳 pear 模組 HTTP_Upload | 小惡魔 - 電()