PHP利用header()下載檔案,來隱藏路徑並解決檔案超過 memory_limit 限制

檔案下載可直接使用 <a href="[filepath]">檔案下載</a>來直接下載檔案,但路徑卻會輕易被得知,之後只要有心人複製 [filepath]貼到瀏覽器,就可以直接下載,而無需透過網頁點選。
此時可利用header來隱藏檔案連結路徑。
1. 先用 SQL資料表,存取檔案路徑與產生該路徑之唯一鍵,如以下
  $filekey = md5( [filepath] );
  製作PHP來製作 $filekey 與 $filepath 之對應。
利用 POST 或 GET 來傳遞 filekey ,傳遞前使用 urlencode()來編碼,再利用 urldecode()
來解出 $filekey 並搜尋出相對應的 $filepath。

2. 接著利用 header() 來下載 filepath,利用 finfo 類別來偵測檔案類型:
<?php
  $finfo = finfo_open(FILEINFO_MIME);
  header('Content-Type: '.finfo_file($finfo, $filepath));
  header('Content-Description: File Transfer');
  header('Content-Transfer-Encoding: binary');
  header('Cache-control: private');
  header("Content-Length: ". (string)filesize($filepath));
  header("Content-Disposition: attachment; filename=".basename($filepath));
  ob_clean();
  ob_flush();
  readfile($filepath);

  /*  以下修正檔案超過 memory_limit 大小造成之錯誤  */
 
  while (!feof($fp))
    {
    echo fread($fp, 65536);
    ob_flush();
    }
  fclose($fp);

  finfo_close($finfo);

?>

參考資料
 http://php.net/manual/en/function.finfo-open.php

 http://php.net/manual/en/function.readfile.php

 https://stackoverflow.com/questions/11646681/php-header-download-cannot-open-file-it-does-not-appear-to-be-a-valid-archive

 

這個網誌中的熱門文章

Upgrade php and httpd(apache) on CentOS 7

Installing VMware workstation pro on Ubuntu 22.X (Jammy Jellyfish)