PHP 檔案系統 fileowner() 函式



PHP 檔案系統fileowner()函式用於返回給定檔案的使用者 ID(所有者)。此函式在成功時返回使用者 ID,在失敗時返回 false。

此函式的結果可以被快取,因此我們可以使用 clearstatcache() 函式清除快取。此函式不能在 Windows 系統上執行。我們可以使用 posix_getpwuid() 函式將使用者 ID 轉換為使用者名稱。

語法

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

int fileowner ( string $filename )

引數

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

序號 引數及描述
1

filename(必需)

它是要獲取其所有者的檔案的路徑。

返回值

如果成功,它將返回檔案所有者的使用者 ID(UID);如果函式失敗,它將返回 FALSE。

PHP 版本

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

示例

這是顯示 PHP 檔案系統fileowner()函式用法的基本示例,其中我們嘗試獲取路徑中提供的檔案的所有者。

<?php
   // echo the Owner ID of the file 
   echo fileowner("/PhpProject/sample.txt");
?>

輸出

這將產生以下結果:

0

示例

在下面的 PHP 程式碼中,我們將使用fileowner()函式,並在無法獲取檔案 ID 或檔案不存在的情況下處理錯誤。

<?php
   // Provide file path here
   $filename = "/PhpProject/myfile.txt";
   
   // use fileowner() function to get file ID
   $owner = fileowner($filename);

   // Handle the error here
   if ($owner !== false) {
      echo "The owner of the file is: " . $owner;
   } else {
      echo "Failed to get the owner of the file.";
   }
?> 

輸出

這將生成以下結果:

The owner of the file is: 501

示例

fileowner()函式用於獲取給定目錄的所有者,在本例中為“uploads/”目錄。程式碼檢查函式是否返回有效的使用者 ID。

<?php
   $uploadDir = "uploads/";
   $owner = fileowner($uploadDir);

   if ($owner !== false) {
      echo "The owner of the upload directory is: " . $owner;
   } else {
      echo "Failed to get the owner of the upload directory.";
   }
?> 

輸出

這將建立以下結果:

The owner of the upload directory is: 302

示例

下面的示例使用fileowner()函式檢查錯誤日誌檔案 error_log 的所有者,並將其值作為所有者 ID 返回。

<?php
   // define the log file here
   $logFile = "error_log";

   // get the owner id of the file
   $owner = fileowner($logFile);

   // perform error handling
   if ($owner !== false) {
      echo "The owner of the log file is: " . $owner;
   } else {
      echo "Failed to get the owner of the log file.";
   }
?> 

輸出

這將導致以下結果:

The owner of the log file is: 1001

注意

您應該驗證以確保指令碼具有訪問檔案的正確許可權,並且該檔案確實存在。當需要檔案所有權進行日誌記錄、檔案管理或安全檢查時,此函式非常有用。

總結

可以使用名為fileowner()的內建 PHP 函式獲取檔案或目錄所有者的使用者 ID(UID)。它僅將檔案路徑作為引數,如果找不到 UID,則返回 false。此功能存在於所有版本的 PHP 中,並且是需要檔案所有者驗證的任務所必需的。

php_function_reference.htm
廣告