PHP 檔案系統 diskfreespace() 函式



PHP 檔案系統 diskfreespace() 函式用於查詢磁碟或目錄上的可用空間量。此函式是 disk_free_space() 函式的別名。

語法

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

float or integer diskfreespace(directory)

引數

使用 diskfreespace 函式所需的引數如下所示:

序號 引數及描述
1

directory(必需)

將要掃描的目錄。

返回值

如果 diskfreespace() 函式成功,則返回可用位元組數。如果發生錯誤,則返回 FALSE。

PHP 版本

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

示例

這是一個基本示例,用於演示 PHP 檔案系統 diskfreespace() 函式的使用。請檢視以下程式碼示例:

<?php
   // This is the root directory.
   $directory = "/";  
   $freeSpace = diskfreespace($directory);

   echo "Free space available in the root directory: " . $freeSpace . " bytes";
?>

輸出

這將生成以下結果:

Free space available in the root directory: 129400332288 bytes

示例

在以下程式碼中,我們將嘗試使用 diskfreespace() 函式查詢指定目錄中的可用空間。請檢視以下程式碼:

<?php
   // Display the free disk space on drive C:
   echo diskfreespace("C:");

   // Output a new line for formatting
   echo "\n";
   
   // Display the free disk space on drive E:
   echo diskfreespace("E:");
?>

輸出

這將產生以下結果:

224159571968
209571344384

示例

此示例查詢指定目錄中的可用空間。因此,在使用 diskfreespace() 函式後,將檢索並顯示以位元組為單位的可用空間。

<?php
   // Mention directory path here
   $directory = "/var/www";

   //Use diskfreespace() to get the free space of the above directory
   $freeSpace = diskfreespace($directory);

   // Echo or print the free space in bytes
   echo "Free space in /var/www: " . $freeSpace . " bytes";
?> 

輸出

這將建立以下結果:

Free space in /var/www: 11686955416 bytes

示例

此示例將根目錄中的可用空間從位元組轉換為兆位元組,以提高可讀性,並以 MB 為單位顯示結果。

<?php
   // Mention directory path here
   $directory = "/";

   //Use diskfreespace() to get the free space of the above directory
   $freeSpace = diskfreespace($directory);

   // Convert in mega bytes (MB)
   $freeSpaceInMB = $freeSpace / (1024 * 1024);

   // Echo or print the free space in bytes
   echo "Free space in the root directory: " . $freeSpaceInMB . " MB";
?> 

輸出

這將導致以下結果:

Free space in the root directory: 111455.765625 MB

示例

在此示例中,我們包含了錯誤處理。如果找不到目錄,它會輸出錯誤訊息並檢查 diskfreespace() 是否返回 FALSE,這表示發生了錯誤。

<?php
   // Mention directory path here
   $directory = "/nonexistent";

   //Use diskfreespace() to get the free space of the above directory
   $freeSpace = diskfreespace($directory);

   // Handle error here for nonexistent directory
   if ($freeSpace === FALSE) {
      echo "Error: Could not find the free space for the given directory.";
   } else {
      echo "Free space in ". $directory . ": " . $freeSpace . " bytes";
   }
?> 

輸出

此 PHP 程式碼的結果為:

Error: Could not find the free space for the given directory.

注意

  • 此函式返回一個位元組值。因此,您可以選擇將其轉換為千兆位元組 (GB)、兆位元組 (MB) 或千位元組 (KB),以方便理解。
  • 如果給定的目錄不存在或存在錯誤,則該函式可能無法返回預期結果。

總結

使用 PHP diskfreespace() 方法查詢磁碟或目錄上的可用空間量。您必須輸入要檢查的目錄或磁碟的路徑作為輸入。

php_function_reference.htm
廣告