PHP 檔案系統 disk_total_space() 函式



PHP 檔案系統 **disk_total_space()** 函式可用於查詢檔案系統或磁碟分割槽(以位元組為單位)的總大小。這對於跟蹤磁碟使用情況、驗證操作是否有足夠的空間或允許訪問磁碟資料非常有用。

給定包含目錄的字串,**disk_total_space()** 函式可以返回相應檔案系統或磁碟分割槽上的總位元組數。

語法

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

float disk_total_space ( string directory )

引數

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

序號 引數及描述
1

directory(必需)

將要掃描的目錄。

返回值

它返回可用總磁碟空間的總位元組數(浮點值),或者在失敗時返回 FALSE。

PHP 版本

**disk_total_space()** 函式作為核心 PHP 4.1.0 的一部分提供,並且與 PHP 5、PHP 7、PHP 8 相容。

示例

在下面的示例中,我們將看到透過傳遞磁碟名稱作為引數來使用 PHP 檔案系統 **disk_total_space()** 函式的基本用法,它將返回以位元組為單位的可用總磁碟空間。

<?php
   echo disk_total_space("C:");
   echo "\n";
   echo disk_total_space("E:");
?>

輸出

這將產生以下結果:

277320036352
209714147328

示例

使用下面的 PHP 程式碼,我們將嘗試使用 **disk_total_space()** 函式獲取指定資料夾的總磁碟空間。

<?php
   // assign directory or folder here
   $directory = '/home/user/Documents';

   // get the total disk space of the specified folder
   $total_space = disk_total_space($directory);

   //print the total disk space
   echo "Total disk space in directory $directory: " . $total_space . " bytes";
?> 

輸出

這將生成以下輸出:

Total disk space in directory /home/user/Documents: 245107195904 bytes

示例

現在,我們將建立一個程式來查詢多個目錄的總磁碟空間。為此,我們將建立一個目錄陣列,並使用 **disk_total_space()** 函式和 foreach 迴圈獲取總磁碟空間。

<?php
   // assign directories or folders here
   $directories = ['/var/www/html', '/var/log'];

   // get the total disk space of each folder
   foreach ($directories as $dir) {
      $total_space = disk_total_space($dir);
      echo "Total disk space in directory $dir: " . $total_space . " bytes<br>";
   }
?> 

輸出

這將導致以下結果:

Total disk space in directory /var/www/html: 245107195904 bytes
Total disk space in directory /var/log: 135506286782 bytes

示例

現在,我們將建立一個 PHP 程式來處理意外錯誤。例如,如果提到的目錄不存在,我們應該如何處理這類錯誤,這在下面的程式碼中解釋。

<?php
   // non existent directory
   $directory = '/nonexistent/directory';

   //find the total disk space
   $total_space = disk_total_space($directory);

   //Handle the error
   if ($total_space === false) {
      echo "Error to get total disk space for directory: $directory";
   } else {
      echo "The total disk space in directory $directory: " . $total_space . " bytes";
   }
?> 

輸出

這段 PHP 程式碼的結果是:

Error to get total disk space for directory: /nonexistent/directory

注意

  • 許多作業系統可以使用此方法,但目錄路徑格式(例如,基於 Unix 的系統上的“/”,Windows 上的“C:\”)可能會有所不同。
  • 此方法不能應用於遠端檔案,因為要檢查的檔案需要透過伺服器的檔案系統訪問。

總結

透過熟悉 **disk_total_space()** 函式,您可以輕鬆管理和監控 PHP 應用程式中的磁碟空間。

php_function_reference.htm
廣告