PHP - 下載檔案



大多數現代瀏覽器允許自動下載某些型別的檔案,而無需任何伺服器端程式碼,例如 PHP 指令碼。例如,zip 檔案或 EXE 檔案。

如果 HTML 超連結指向 ZIP 或 EXE 檔案,瀏覽器會下載它並彈出儲存對話方塊。但是,文字檔案、影像檔案等不會下載,而是在瀏覽器中開啟,您可以將其儲存到本地檔案系統。

readfile() 函式

要下載此類檔案(而不是瀏覽器自動開啟它們),我們可以在 PHP 的內建函式庫中使用readfile() 函式。

readfile(string $filename, 
bool $use_include_path = false, 
?resource $context = null)
: int|false

此函式讀取檔案並將其寫入輸出緩衝區。

第二個引數$use_include_path 預設情況下為 false,因此當前目錄中的檔案將被下載。如果設定為true,則將搜尋新增到php.ini 配置的include_path 設定中的目錄以找到要下載的檔案。

readfile() 函式返回讀取的位元組數或 false,即使它已成功完成或未完成。

示例

以下 PHP 指令碼顯示了 readfile() 函式的使用。

要下載檔案,Content-Type 響應頭應設定為application/octect-stream。此 MIME 型別是二進位制檔案的預設型別。瀏覽器通常不會執行它,甚至不會詢問是否應該執行它。

此外,將 Content-Disposition 標頭設定為 attachment 會提示彈出“另存為”對話方塊。

<?php
   $filePath = 'welcome.png';

   // Set the Content-Type header to application/octet-stream
   header('Content-Type: application/octet-stream');

   // Set the Content-Disposition header to the filename of the downloaded file
   header('Content-Disposition: attachment; filename="'. basename($filePath).'"');

   // Read the contents of the file and output it to the browser.
   readfile($filePath);
?>

將上述指令碼儲存為文件根資料夾中的“download.php”。確保要下載的檔案位於同一資料夾中。

啟動伺服器並在瀏覽器中訪問https:///download.php。您將獲得如下所示的“另存為”對話方塊 -

PHP Download File

您可以選擇名稱並下載檔案。

對於大型檔案,您可以從檔案流中以特定預定義大小的塊讀取它。如果 Content-Disposition 頭設定為“attachment”(如前面的示例所示),瀏覽器會提供將其儲存到本地檔案系統中。

<?php
   $filename = 'welcome.png';

   header('Content-Type: application/octet-stream');
   header('Content-Disposition: attachment; filename="' . basename($filename) . '"');

   $handle = fopen($filename, 'rb');
   $buffer = '';
   $chunkSize = 1024 * 1024;

   ob_start();
   while (!feof($handle)) {
      $buffer = fread($handle, $chunkSize);		
      echo $buffer;
      ob_flush();
      flush();
   }
   fclose($handle);
?>
廣告

© . All rights reserved.