PHP chown() Function

What is PHP chown() Function?

If you want to change the owner of a file to another one, use chown() function. You can change the owner of a file if you are a superuser or running with root privilege.

What is group in a file/directory? In Unix based operating system, the file control mechanism determines who can access a file/folder and what they can do with it. There are three type of users of each file/folder – owner (who own it), group (who share the same permission), and other (all the users except owner and group).

Syntax:

chown(filename, user)

Parameters:

The Function has 2 required parameters-

filename (Required): It is the path to the file or folder whose owner you want to change.

user (Required): It is the new user that you want to set. It could be a string or a number. When you mention name as a user, then it is a string. On the other hand, when you mention user id, then it is a number.

Return Values:

The function returns-

  • TRUE – if it successfully changes the owner.
  • FALSE – if it can’t change the owner.

Examples:

Example 1: Changing owner by user name-

<?php
chown("docs/dl.pdf", "john");
?>

Explanation:

The function changes owner of the file dl.pdf to “john”.

Example 2: Changing owner by owner id-

<?php
chown("docs/dl.pdf", 8);
?>

Explanation:

The function changes owner of the file dl.pdf to the owner whose id is 8.

Example 3: Confirming file ownership change-

<?php
if (chown("docs/dl.pdf", "john")) {
    echo "File owner changed.";
} else {
    echo "File owner didn't change.";
}
?>

Output:

File owner changed.

Explanation:

Line 2: The function changes owner of the file dl.pdf to “john” and returns TRUE and prints the message on line 3.

Best Practices on chown() Function:

  • As the function returns TRUE on success and FALSE on failure, it is good practice to check the function’s success with conditional statement. Check example 2.

Notes on chown() Function:

  • On Windows system, this function doesn’t work.
  • This function can’t work on remote files as it can’t access the filesystem.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP chown() Function

chown() is one of the filesystem functions in PHP which is used to change the owner of a file. It helps you to manage your files and directories assigning proper ownership.

Reference:

https://www.php.net/manual/en/function.chown.php