Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP Filesystem link() Function



The PHP Filesystem link() function is used to create a hard link for a file. This function mainly work for local files it does not work on remote files.

A hard link is an alternative name for an existing file. When you create a hard link, you are directed to the data inside the file. It means that the primary file and the hard link have the same information. If you delete one, the data is still available through the other.

Syntax

Below is the syntax of the PHP Filesystem link() function −

bool link(string $target, string $link)

Parameters

Below are the required parameters of the link() function −

Sr.No Parameter & Description
1

$target(Required)

It is the target of the link.

2

$link(Required)

It is the link name.

Return Value

The function returns TRUE on success or FALSE on failure.

PHP Version

The link() function was first introduced as part of core PHP 4 and work well with the PHP 5, PHP 7 and PHP 8.

Example

Here is the basic example to see how the PHP Filesystem link() function to create a symbolic link.

<?php
    // Your target file
    $target = 'myfile.txt'; 
    
    // Give the name of the link
    $link = 'newfile';
    
    // Create a hard link for the target file
    link($target, $link);

    echo "Hard link has been created!"
?>

Output

Here is the outcome of the following code −

Hard link has been created!

Example

Here is the another example to show the usage of link() function, so using the below code you can create hard link. Here newfile.txt is the hard link and myfile.txt is the original file.

<?php
    $target = "/PhpProject/myfile.txt"; // Original file
    $link  = "/PhpProject/newfile.txt"; // hard link

    if (link($target, $link)) {
        echo 'Hard link created successfully.';
    } else {
        echo 'Failed to create hard link.';
    }
?> 

Output

This will produce the following result −

Hard link created successfully.

Example

Here is one more example to handle the errors while using the link() function.

<?php
    $target = "/PhpProject/myfile.txt"; // Original file
    $link  = "/PhpProject/newfile.txt"; // hard link

    if (link($target, $link)) {
        echo "Hard link created successfully.\n";
    } else {
        $error = error_get_last();
        echo "Failed to create hard link: " . $error['message'] . "\n";
    }
?> 

Output

This will generate the below output, in case of Success −

Hard link created successfully.

In case of Failure, it will generate the following error −

Failed to create hard link: Operation not permitted

Summary

The link() method is a built-in function to create a hard link for files. It returns true on success and false on failure. And this function is helpful when you need multiple references to a single file so it prevent duplication of the data.

php_function_reference.htm
Advertisements