PHP 檔案系統 readfile() 函式



PHP 檔案系統readfile()函式用於讀取檔案並將其寫入輸出緩衝區。此函式在成功時可以返回讀取的位元組數,或者在失敗時返回false和錯誤。我們可以透過在函式名前新增“@”來隱藏錯誤輸出。

如果在 php.ini 檔案中啟用了 fopen() 函式包裝器,則可以使用 URL 作為此函式的檔名。

語法

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

int readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]] )

引數

以下是readfile()函式的必需和可選引數:

序號 引數和描述
1

$filename(必需)

要讀取的檔案。

2

$use_include_path(可選)

將此選項設定為 true 以在 include_path 中查詢檔案。include_path 可以在 php.ini 中指定。

3

$context(可選)

這是一個上下文流資源。上下文是一組可能更改流行為的設定。

返回值

readfile()函式在成功時返回從檔案中讀取的位元組數,在失敗時返回 FALSE。

PHP 版本

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

示例

這是一個基本示例,用於演示如何使用 PHP 檔案系統readfile()函式讀取給定的檔案。

首先將內容寫入 sample.txt 檔案中。以下是寫入檔案的內容。

Hello World!
Tutorialspoint
Tutorix
32

現在執行以下 PHP 程式碼以檢視 readfile() 函式的結果:

<?php
   echo "Read the content of sample.txt file:";
   echo readfile("/PhpProject/sample.txt");
?>

輸出

以下是以下程式碼的結果:

Read the content of sample.txt file:
Hello World!
Tutorialspoint
Tutorix
32

示例

以下是一個使用readfile()函式處理使用它時出現的錯誤的示例。

<?php
   $filename = "/PhpProject/testfile.txt";

   // Check if the file exists
   if (file_exists($filename)) {
      // Read and display the content of the file
      readfile($filename);
   } else {
      echo "File does not exist.";
   }
?> 

輸出

這將產生以下結果:

File does not exist.

示例

以下是一個使用readfile()函式讀取 .jpg 等不同檔案格式的示例。

<?php
   $filename = "/PhpProjects/image.jpg";

   // Check if the file exists
   if (file_exists($filename)) {
      // Set the content type header to display the image
      header('Content-Type: image/jpeg');
      
      // Read and output the image file
      readfile($filename);
   } else {
      echo "File does not exist.";
   }
?> 

輸出

這將生成以下輸出:

This code will show the image on the screen specified in the filename.

示例

以下是一個使用readfile()函式下載檔案並在設定標題以觸發下載後的示例。

<?php
   $filename = "/PhpProjects/myfile.pdf";

   // Check if the file exists
   if (file_exists($filename)) {
       // Set headers to trigger a download
       header('Content-Description: File Transfer');
       header('Content-Type: application/octet-stream');
       header('Content-Disposition: attachment; filename="'.basename($filename).'"');
       header('Expires: 0');
       header('Cache-Control: must-revalidate');
       header('Pragma: public');
       header('Content-Length: ' . filesize($filename));
       
       // Read and output the file
       readfile($filename);
       echo "The file has been downloaded."
       exit;
   } else {
       echo "File does not exist.";
   }
?> 

輸出

這將導致以下輸出:

The file has been downloaded.

總結

readfile()方法是一個內建函式,用於讀取給定的檔案。它對於在網頁上顯示檔案內容或允許檔案下載非常有用。

php_function_reference.htm
廣告