PHP 檔案系統 fclose() 函式



PHP 檔案系統fclose()函式用於關閉檔案。這很重要,因為它可以節省資源並確保所有資料都正確寫入檔案。因此,此函式能夠關閉任何開啟的檔案。

檔案指標必須有效,並且必須指向由 fopen() 或 fsockopen() 函式成功開啟的檔案。

語法

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

bool fclose ( resource $handle )

引數

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

序號 引數及描述
1

handle (必需)

檔案指標需要指向由 fopen() 或 fsockopen() 成功開啟的有效檔案。

返回值

成功返回 TRUE,失敗返回 FALSE。

PHP 版本

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

示例

在下面的 PHP 程式碼中,我們將向您展示 PHP 檔案系統fclose()函式的基本用法。請檢視下面的程式碼示例:

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

   // Close the file handle
   fclose($handle);

   // Print a message 
   echo "The file is successfully closed.";
?>

輸出

這將產生以下結果:

The file is successfully closed.

示例

我們將建立一個小型程式來演示使用fclose()函式關閉給定檔案的用法。請檢視下面的 PHP 程式碼:

<?php
   // Define handle here
   $handle = fopen("/PhpProject/sample.txt", "r");

   // close the file here using fclose()
   fclose($handle);

   //echo the message 
   echo "File closed successfully";
?>

輸出

這將生成以下結果:

File closed successfully

示例

在下面的程式碼中,我們將嘗試開啟檔案並在其上執行寫入操作,然後使用 PHP 中的fclose()函式關閉它。

<?php
   // Open a file for writing
   $file = fopen("myfile.txt", "w");

   // Write some content to the file
   fwrite($file, "Hello, world!");

   // Close the file
   fclose($file);

   echo "File Closed Successfully.";
?> 

輸出

這將建立以下結果:

File Closed Successfully.

示例

考慮這樣一種情況:您必須開啟多個檔案,並且需要關閉它們。在這種情況下,您可以使用fclose()函式關閉所有開啟的檔案。

<?php
   // Open first file for reading
   $file1 = fopen("file1.txt", "r");

   // Open second file for writing
   $file2 = fopen("file2.txt", "w");

   // Perform operations on files...

   // Close the first file
   fclose($file1);

   // Close the second file
   fclose($file2);

   echo "All the files has been closed successfully.";
?> 

輸出

這將導致以下結果:

All the files has been closed successfully.

示例

假設您要開啟一個檔案,並在向其追加一些內容後關閉該檔案。在這種情況下,您可以使用fclose()函式關閉檔案。

<?php
   // Open a file for appending
   $file = fopen("log.txt", "a");

   // Append some data to the file
   fwrite($file, "User logged in at " . date("Y-m-d H:i"));

   // Append more data...
   fwrite($file, "User performed some action at " . date("Y-m-d H:i"));

   // Close the file
   fclose($file);

   echo "File closed successfully.";
?> 

輸出

此 PHP 程式碼的結果是:

File closed successfully.

注意

為了確保資料完整性和節省資源,您應該在完成檔案操作後始終使用fclose()

總結

PHP 中的fclose()函式可用於關閉開啟的檔案。此方法對於有效的資源管理和資料完整性都是必要的。

php_function_reference.htm
廣告