PHP 檔案系統 chown() 函式



PHP 檔案系統chown()函式用於更改指定檔案的擁有者。只有超級使用者才能使用此函式更改檔案的所有者。成功返回 true,否則返回 false。

語法

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

bool chown ( string filename, string/int user )

引數

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

序號 引數及描述
1

filename(必填)

需要更改其所有者的檔案路徑。

2

user(必填)

檔案的新的所有者。可以是使用者名稱、使用者 ID 或數字。

返回值

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

PHP 版本

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

示例

下面的程式碼使用 PHP 檔案系統chown()函式將 myfile.txt 的所有者更改為使用者 root,然後列印有關檔案新所有者的詳細資訊。

我們還使用了 stat() 和 posix_getpwuid() 函式。stat() 獲取有關檔案的資訊,而 posix_getpwuid() 透過使用者 ID 獲取使用者資訊。

<?php
   // File name and username to use
   $filename= "myfile.txt";
   $dirpath = "/Applications/XAMPP/xamppfiles/htdocs/mac/" . $filename ;
   $user_name = "root";
    
   // Set the user
   chown($dirpath, $user_name);
    
   // Check the result
   $stat = stat($dirpath);
   print_r(posix_getpwuid($stat['uid']));
?>

輸出

這將產生以下結果:

Array ( 
   [name] => root 
   [passwd] => ******** 
   [uid] => 501 
   [gid] => 20 
   [gecos] => root
   [dir] => /root 
   [shell] => /bin/zsh 
)

示例

在本例中,我們將嘗試將位於使用者主目錄中的名為“myfile.txt”的檔案的所有者更改為名為“nick”的使用者。當更改訪問許可權或需要許多使用者控制系統內的同一檔案時,這將非常有用。

<?php
   // Define the file name and path
   $filename = "myfile.txt";

   $dirpath = "/home/nick/documents/" . $filename;

   // Define the user name
   $user_name = "nick";

   // Change the owner of the file to "nick"
   chown($dirpath, $user_name);

   echo "Changed Owner for User's Home Directory is: ". $user_name;
?> 

輸出

這將生成以下結果:

Changed Owner for User's Home Directory is: nick

示例

此 PHP 程式碼將把檔案或目錄的所有者更改為 web 伺服器的“www-data”,方法是將所有權轉移到 web 伺服器軟體用於訪問和提供 web 內容的使用者帳戶。

<?php
   // declare the file name and path
   $filename = "index.html";
   $dirpath = "/var/www/html/" . $filename;

   // declare the user name
   $user_name = "www-data";

   // change the owner of the file to "www-data"
   chown($dirpath, $user_name);

   // check the result
   $stat = stat($dirpath);
   print_r(posix_getpwuid($stat['uid']));
?> 

輸出

這將產生以下結果:

Array ( 
   [name] => root 
   [passwd] => * 
   [uid] => 0 [gid] => 0 
   [gecos] => System Administrator 
   [dir] => /var/root 
   [shell] => /bin/sh 
)

示例

在本例中,我們將更改 FTP 目錄中“upload.txt”檔案的所有者為名為 ftpuser 的使用者。此使用者使用 FTP 處理檔案。

<?php
   $filename = "upload.txt";
   $dirpath = "/home/ftpuser/ftp/" . $filename;

   // Define the user name
   $user_name = "ftpuser";

   // Change the owner of the file to "ftpuser"
   chown($dirpath, $user_name);

   // Check the result
   $stat = stat($dirpath);
   print_r(posix_getpwuid($stat['uid']));
?> 

輸出

這將產生以下結果:

Array ( 
   [name] => root 
   [passwd] => * 
   [uid] => 0 [gid] => 0 
   [gecos] => System Administrator 
   [dir] => /var/root 
   [shell] => /bin/sh 
)

注意

  • 在 Windows 平臺上,此功能不可用。
  • 此函式無法處理遠端檔案,因為它無法訪問檔案系統。

總結

PHP 檔案系統函式chown()可用於更改檔案的所有者。透過賦予適當的所有權,可以更輕鬆地處理目錄和檔案。

php_function_reference.htm
廣告