chown

(PHP 4, PHP 5, PHP 7, PHP 8)

chownChanges file owner

Description

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

Attempts to change the owner of the file filename to user user. Only the superuser may change the owner of a file.

Parameters

filename

Path to the file.

user

A user name or number.

Return Values

Returns true on success or false on failure.

Examples

Example #1 Simple chown() usage

<?php

// File name and username to use
$file_name= "foo.php";
$path = "/home/sites/php.net/public_html/sandbox/" . $file_name ;
$user_name = "root";

// Set the user
chown($path, $user_name);

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

?>

The above example will output something similar to:

Array
(
    [name] => root
    [passwd] => x
    [uid] => 0
    [gid] => 0
    [gecos] => root
    [dir] => /root
    [shell] => /bin/bash
)

Notes

Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.

Note: On Windows, this function fails silently when applied on a regular file.

See Also

add a note

User Contributed Notes 2 notes

up
7
martijn at sigterm dot nl
21 years ago
If chown is filled with a variable ( chown ("myfile", $uid) the uid will be looked up through pwget_uid.

So if you need to set a non existing uid use inval($uid).
up
0
mindlessconsumer+phpnet at gmail dot com
2 days ago
It may be worth making explicitly clear that, while the shell's `chown` command allows both user and group to be set in one system call like this `chown username:groupname filename`, PHP's version unfortunately does not:

<?php
// This will not work.
chown($filename, 'username:groupname');

// You have to use two separate calls.
chown($filename, 'username');
chgrp($filename, 'groupname');
?>
To Top