如何透過 PHP 指令碼下載大檔案?


要透過 PHP 指令碼下載大檔案,程式碼如下:

示例

<?php
function readfile_chunked($filename,$retbytes=true) {
   $chunksize = 1*(1024*1024); // how many bytes per chunk the user wishes to read
   $buffer = '';
   $cnt =0;
   $handle = fopen($filename, 'rb');
   if ($handle === false) {
      return false;
   }
   while (!feof($handle)) {
      $buffer = fread($handle, $chunksize);
      echo $buffer;
      if ($retbytes) {
         $cnt += strlen($buffer);
      }
   }
   $status = fclose($handle);
   if ($retbytes && $status) {
      return $cnt; // return number of bytes delivered like readfile() does.
   }
   return $status;
}
?>

輸出

這將產生以下輸出:

The large file will be downloaded.

函式 ‘readfile_chunked’(使用者自定義)接受兩個引數 - 檔名和 ‘true’ 的預設值,表示返回的位元組數,這意味著大檔案已成功下載。變數 ‘chunksize’ 已宣告為需要讀取的每個塊的位元組數。 ‘buffer’ 變數被賦值為 null, ‘cnt’ 被設定為 0。檔案以二進位制讀取模式開啟並賦值給變數 ‘handle’。

直到 ‘handle’ 的檔案結尾,while 迴圈執行並根據需要讀取的塊數讀取檔案內容。接下來它顯示在螢幕上。如果 ‘retbytes’(函式的第二個引數)的值為 true,則將緩衝區的長度新增到 ‘cnt’ 變數。否則,關閉檔案並返回 ‘cnt’ 值。最後,函式返回 ‘status’。

更新於: 2020-04-09

2K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.