PHP 檔案系統 fpassthru() 函式



PHP 檔案系統fpassthru()函式用於讀取從開啟檔案中的當前位置到檔案結尾 (EOF) 的所有資料。它還可以將結果寫入輸出緩衝區。此函式可以返回傳遞的字元數,或者在失敗時返回 false。

當我們在 Windows 系統上的二進位制檔案中使用fpassthru()函式時,必須以二進位制模式開啟檔案。

語法

以下是 PHP 檔案系統fpassthru()函式的語法:

int fpassthru ( resource $handle )

引數

使用fpassthru()函式所需的引數如下:

序號 引數及說明
1

handle (必需)

這是由 fopen() 建立的檔案指標資源。

返回值

它返回從檔案指標讀取的位元組數。如果發生錯誤,它將返回 FALSE。

PHP 版本

fpassthru()函式最初作為核心 PHP 4 的一部分引入,並且與 PHP 5、PHP 7、PHP 8 相容良好。

示例

在下面的 PHP 程式碼中,我們將開啟一個檔案並讀取它的第一行。接下來,它使用 PHP 檔案系統fpassthru()函式將檔案的其餘部分(從第二行開始)回顯到輸出緩衝區。

<?php
   $file = fopen("/PhpProject/sample.txt", "r");
 
   // Read first line
   fgets($file);

   // Send rest of the file to the output buffer
   echo fpassthru($file);
   fclose($file);
?>

輸出

上述 PHP 程式碼的輸出為:

Tutorix7

示例

在這個示例中,我們將開啟一個檔案並定義下載檔案的標頭。它透過使用fpassthru()函式將檔案傳送到使用者的瀏覽器來啟動檔案下載。

<?php
   // Define the file path and open it
   $file = fopen("/Applications/XAMPP/xamppfiles/htdoc/mac/myfile.txt", "rb");

   //Define the content type
   header("Content-Type: application/octet-stream");

   header("Content-Disposition: attachment; filename='example.txt'");
   
   //Send data of file to browser
   fpassthru($file);

   //Close the file
   fclose($file);
?> 

輸出

這將生成以下結果:

# The provided code will result in a file download prompt on the user's browser. The content is being received directly from the server, and the file that is being downloaded is called "myfile.txt".

示例

在這個示例中,我們將開啟一個 JPEG 圖片檔案,並設定相應的 content-type 標頭。我們將使用fpassthru()函式將影像內容直接輸出到瀏覽器。

<?php
   // Open the image file here
   $image = fopen("image.jpg", "rb");

   //Define the content type
   header("Content-Type: image/jpeg");

   // Send image file to browser
   fpassthru($image);

   //Close the file
   fclose($image);
?> 

輸出

這將產生以下結果:

The output of this code would be displaying the image "image.jpg" directly in the browser.

示例

現在,我們將嘗試使用fpassthru()函式和將內容型別定義為影片來流式傳輸影片檔案。

因此,程式碼開啟 "video.mp4" 影片檔案並將影片內容型別標頭設定為 video/mp4。此外,"Accept-Ranges" 標頭用於方便在影片內搜尋。

<?php
   // Open the video file here
   $video = fopen("video.mp4", "rb");

   //Define the content type as video or mp4
   header("Content-Type: video/mp4");
   header("Accept-Ranges: bytes");

   //Send data to the user's browser
   fpassthru($video);

   //Close the file here
   fclose($video);
?> 

輸出

這將導致以下結果:

# The output of this code will be streaming the video "video.mp4" directly in the browser's video player.

注意

在呼叫fpassthru()之前,務必使用 header() 等函式建立正確的標頭,以定義內容型別並開始必要的操作,例如檔案下載或內聯顯示。

總結

fpassthru()方法將檔案內容直接流式傳輸到瀏覽器或輸出緩衝區,此函式的特性使其成為管理檔案下載、流式傳輸影片或類似場景的 Web 應用程式的有用工具。

php_function_reference.htm
廣告