The basic syntax of the link() function is as follows:
<code>link(string $target, string $link)</code>
$target is the existing target file path
$link is the hard link path to be created
Example:
<code> <?php $target = "gitbox.net/files/original.txt"; $link = "gitbox.net/files/hardlink.txt"; if (link($target, $link)) {
echo "Hard link was created successfully!";
} else {
echo "Creating hard link failed.";
}
?>
</code>
A hard link is essentially multiple directory entries that point to the same file data, so:
Permission Sharing <br> Hard links and original file share the same permission settings as they point to the same file content and metadata. This means that the permissions are the same regardless of the path through which the file is accessed.
Impact of permission modification <br> Making permission modifications to hard links or original files is actually modifying the permissions of the file itself, and all links will be affected.
The impact of deleting files <br> Delete one of the hard links, just delete the directory item, the file data still exists, as long as there are other hard links.
Suppose there is a file gitbox.net/files/original.txt permission is 0644 (owner can read and write, other users can read):
<code> <?php $target = "gitbox.net/files/original.txt"; $link = "gitbox.net/files/hardlink.txt"; // Create hard links
if (link($target, $link)) {
echo "Hard link was created successfully.\n";
}
// View permissions
echo sprintf("Permissions: %o\n", fileperms($target) & 0777);
// Modify permissions
chmod($link, 0666);
echo "After modifying hard link permissions: \n";
echo sprintf("original file permissions: %o\n", fileperms($target) & 0777);
echo sprintf("Hard link permissions: %o\n", fileperms($link) & 0777);
?>
</code>
The running results show that after modifying the permissions of the hard link, the original file permissions were also modified because they were different paths to the same file.
Hard links can only be created within the same file system, and cannot be cross-partitions or cross-mount points.
Directory files usually do not allow hard links (Linux restrictions) and can only be used on ordinary files.
Soft links (symlinks) are different from hard links, and soft link permissions and target file permissions are not related.
PHP's link() function creates a hard link, and multiple links share the same file permissions.
Modifying the permissions of the hard link or the original file will affect all links to the file.
Hard links are suitable for scenarios where multi-path access is required for data consistency.
By understanding the interaction mechanism between PHP's link() function and file permissions, we can better manage the file system and avoid permission chaos and misoperation.