What is the chown() function in PHP?

chown() is a built-in function in PHP that changes the owner or user group of a file. Only the superuser has the privileges to change the ownership of a file.

Syntax

chown(string $filename, string|int $user): bool

Parameters

  • filename: The name of the file as a string.
  • user: The name of the user as either a string or an integer.

Return value

chown() returns true on success and false on failure.

Code

main.php
temp
<?php
$file_name= "temp";
$path = "./" . $file_name ;
$user_name = "root";
chown($path, $user_name);
$stat = stat($path);
$usr = strval($stat['uid']);
print_r("UID: ".$usr."(root)\n");
print_r(posix_getpwuid($stat['uid']));
?>

The code above shows how the chown() function is used. We provide the user_name and path to chown() and it changes the owner to user_name. The stat() function provides information about a file, which is the temp file in this case. Lastly, we print the UID, which is 0. This denotes that the UID of the file’s owner is indeed root.

Copyright ©2024 Educative, Inc. All rights reserved