PHP 檔案系統 pclose() 函式



PHP 檔案系統 pclose() 函式用於關閉由 popen() 開啟的管道,並返回執行程序的終止狀態。如果發生錯誤,則可能返回 -1。

語法

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

int pclose ( resource $handle )

引數

以下是 pclose() 函式唯一必需的引數:

序號 引數和說明
1

$handle(必需)

它必須是檔案指標,並且是從對 popen() 的成功呼叫中返回的。

返回值

pclose() 函式返回啟動的操作的結束狀態。如果發生錯誤,則返回 -1。

PHP 版本

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

示例

這是一個基本示例,用於演示如何使用 PHP 檔案系統 pclose() 函式關閉由 popen() 函式開啟的管道。

<?php
   //Open a pipe
   $handle = popen("/bin/ls", "r");

   //Execution of some code

   //Close the pipe
   pclose($handle);
?>

輸出

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

ls: stdout: Broken pipe

示例

這是一個另一個示例,用於演示如何使用 pclose() 函式關閉由 popen() 開啟的管道並列出提到的管道中存在的所有檔案和目錄。

<?php
   // Open a pipe
   $handle = popen("/bin/ls", "r");

   if ($handle) {
      // Read the output from the pipe
      while (($line = fgets($handle)) !== false) {
         echo $line;
      }

      // Close the pipe
      pclose($handle);
   } else {
      echo "Unable to open the pipe.";
   }
?> 

輸出

這將產生以下結果:

config.php
csvfile.csv
data.csv
documents
error_log.log
image.jpg
images
index.php
logo.gif
logs
myfile.txt
new dir
newfile.php
sample.txt
uploads

示例

這是一個另一個示例,用於瞭解 pclose() 函式的使用方法。因此,在這個示例中,我們將使用 df 命令檢查磁碟空間。

命令 '/bin/df -h' 用於 Unix 作業系統。因此,/bin/df 是 df 命令的路徑,df 表示“磁碟空間”。它基本上顯示檔案系統上可用的磁碟空間量。-h 用於將輸出轉換為人類可讀的格式。

<?php
   // Open a pipe to check disk usage
   $handle = popen("/bin/df -h", "r");

   if ($handle) {
      // Read the output from the pipe
      while (($line = fgets($handle)) !== false) {
         echo $line;
      }

      // Close the pipe
      pclose($handle);
   } else {
      echo "We are unable to open the pipe.";
   }
?> 

輸出

這將生成以下輸出:

Filesystem        Size    Used   Avail Capacity iused ifree %iused  Mounted on
/dev/disk3s1s1   228Gi   9.6Gi   123Gi     8%    404k  1.3G    0%   /
devfs            198Ki   198Ki     0Bi   100%     686     0  100%   /dev
/dev/disk3s6     228Gi    20Ki   123Gi     1%       0  1.3G    0%   /System/Volumes/VM

示例

在這個示例中,我們將使用 date 命令檢查當前日期和時間,並使用 pclose() 函式關閉管道。

<?php
   // Open a pipe to display the date and time
   $handle = popen("/bin/date", "r");

   if ($handle) {
      // Read the output from the pipe
      while (($line = fgets($handle)) !== false) {
         echo $line;
      }

      // Close the pipe
      pclose($handle);
   } else {
      echo "We are unable to open the pipe.";
   }
?> 

輸出

這將導致以下輸出:

Mon Jun 24 14:39:11 IST 2024

總結

pclose() 方法是用於關閉已開啟管道的內建函式。popen 函式建立一個管道來執行系統命令,fgets 讀取輸出,pclose 在讀取完成後關閉管道。這是在 PHP 中與系統命令通訊的標準方法。

php_function_reference.htm
廣告