In PHP, lchown() changes the owner of a symbolic link itself. It does not follow the link to the file it points to.
It is the link-safe partner of chown(). Use it when you want to change who owns a link, for example after you deploy a new release folder on a Linux server.
Syntax
Call lchown() with the values you need. Start with this line.
PHP
$ok = lchown('current', 'www-data');
Call
What it does
lchown('current', 'www-data')
Makes www-data the owner of the link named current.
lchown('current', 33)
Does the same job by using the numeric user id.
lchown('missing-link', 'root')
Returns false with a warning because the link does not exist.
lchown() is not available on Windows. On most systems only the superuser (root) can give a link to another user, so this function normally runs inside deployment scripts or command line tools, not inside a normal web request.
Library declarations
PHP
lchown(string $filename, string|int $user): bool
Parameters
Parameter
Description
filename
Required. The path to the symbolic link.
user
Required. A user name as a string, or a user id as an integer.
Return Value
Return Value
Description
bool
Returns true on success or false on failure.
PHP Examples
Example 1 — Change the Owner of a Link
Create a symbolic link and assign it to another user. Run this as root.
PHP
<?php
$link = __DIR__ . '/current';
symlink('releases/v1', $link);
if (lchown($link, 'www-data')) {
echo "Owner of the link changed", PHP_EOL;
} else {
echo "Could not change the owner", PHP_EOL;
}
Output
Owner of the link changed
How It Works
symlink() creates a link named current that points to releases/v1.
lchown() asks the system to make www-data the owner of the link.
Only the link is affected. The folder releases/v1 keeps its own owner.
A true result prints the success message.
Example 2 — Check That the Function Exists
lchown() does not exist on Windows, so test for it before calling it.
PHP
<?php
$link = __DIR__ . '/current';
if (!function_exists('lchown')) {
echo "lchown() is not available here", PHP_EOL;
} elseif (!@lchown($link, 'www-data')) {
echo "Could not change the owner", PHP_EOL;
}
Output
Could not change the owner
How It Works
function_exists() tells you whether the operating system supports lchown().
On Linux the function exists, so the script moves on to the next check.
The call fails because the link is missing or the user has no permission.
The @ hides the warning and the script prints a clear message.
Example 3 — Read the Owner with lstat()
Use lstat() to read the user id of the link itself after changing it.