PHP 檔案系統 fread() 函式



PHP 檔案系統 fread() 函式用於從開啟的檔案中讀取資料,此函式可以在檔案末尾或達到指定長度時停止,以先到者為準。此函式可以返回讀取的字串或在失敗時返回 false。

fread() 函式可以從控制代碼引用的檔案指標中讀取最多 length 個位元組。

語法

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

string fread ( resource $handle , int $length )

引數

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

序號 引數及描述
1

handle(必需)

這是您要從中讀取檔案的指標。

2

length(必需)

要從檔案中讀取的位元組數。

返回值

它返回讀取的字串或在失敗時返回 FALSE。

PHP 版本

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

示例

在下面的 PHP 示例中,我們將使用 PHP 檔案系統 fread() 函式讀取指定長度的檔案內容。

<?php
   // Assign the file path here
   $filename = "/PhpProject/sample.txt";

   // Open the file in reading mode
   $handle = fopen($filename, "r");

   // echo the reading content using fread()
   echo fread($handle, "30");
   
   //Close the file
   fclose($handle);
?>

輸出

以下是以上程式碼的輸出:

Tutorialspoint
Tutorix
Hello

示例

此示例程式碼首先開啟一個名為“sample.txt”的檔案,然後使用 fread() 和 filesize() 函式讀取其所有內容,然後將內容列印到螢幕上。

<?php
   $filename = "/PhpProject/sample.txt";
   $file = fopen($filename, "r");
   
   $contents = fread($file, filesize($filename));
   echo $contents;
   
   fclose($file);
?>

輸出

以下是以上 PHP 程式碼的輸出:

Tutorialspoint
Tutorix
Hello Tutorialspoint!!!!

示例

現在假設您的程式碼無法開啟和讀取指定的檔案,因為檔案不存在或您沒有訪問許可權。那麼,您如何像下面的 PHP 程式碼一樣處理這種情況呢?

<?php
   // Open the file in read mode
   $file = fopen("/PhpProject/myfile.txt", "r");

   // Check if the file opened successfully
   if ($file) {
      // Read 10 bytes from the file
      $content = fread($file, 10);

      // Check if fread was successful
      if ($content !== false) {
         // Display the content
         echo "Read content: " . $content;
      } else {
         echo "Failed to read from the file.";
      }

      // Close the file
      fclose($file);
   } else {
      echo "Failed to open the file.";
   }
?> 

輸出

這將產生以下結果:

Failed to open the file.

示例

以下是一個示例,它演示瞭如何在 fread() 函式的幫助下讀取二進位制檔案的一部分。我們還使用了 bin2hex() 函式,該函式將二進位制資料轉換為其十六進位制形式。

<?php
   // Open the binary file in read mode
   $file = fopen("example.bin", "rb");

   // Check if the file opened successfully
   if ($file) {
      // Read 20 bytes from the file
      $content = fread($file, 20);

      // Check if fread was successful
      if ($content !== false) {
         // Display the content in hexadecimal format
         echo "Read content: " . bin2hex($content);
      } else {
         echo "Failed to read from the file.";
      }

      // Close the file
      fclose($file);
   } else {
      echo "Failed to open the file.";
   }
?> 

輸出

這將生成以下結果:

Read content: 48656c6c6f20576f726c6421a1b2c3d4e5f6a7b8c9da

注意

  • 驗證檔案始終存在且可訪問。
  • 在使用 fread() 之前,請確保 fopen() 成功。
  • 為了優雅地處理錯誤,請處理 fread() 返回的 false 結果。
  • fread() 可以與二進位制檔案和文字檔案一起使用,因為它可以讀取原始二進位制資料。

總結

當您只需要將檔案的特定部分讀取到記憶體中而不是整個檔案時,fread() 函式非常有用。

php_function_reference.htm
廣告