PHP readlink() Function

What is PHP readlink() Function?

To get the physical path of a symbolic link, use PHP readlink() function.

You know symbolic link is a shortcut to an existing file or folder in your server’s file system. You create this symbolic link with symlink() function to easily access any file/folder in your file system. Sometimes you may need to know the path of the file/folder of a symbolic link and readlink() helps you to get that.

Syntax:

readlink(symlink)

Parameters:

The Function has 1 required parameter which is required-

symlink (Required): the name of the symbolic link.

Return Values:

The function returns-

  • Target (physical address) of the symbolic link. – on success
  • FALSE – on failure.

Examples:

Example 1:

<?php
$target = 'test.txt';
$link = 'test';
symlink($target, $link);
echo readlink($link);
?>

Output:

test.txt

Explanation:

The function creates a symbolic link named “test” of the file “test.txt”. The readlink() function shows the physical path of the symbolic file “test” which is “test.txt”.

Example 2:

<?php
if (is_link('test')) {
    $target = readlink('test');
    echo 'The physical address of the symbolic link is: ' . $target;
} else {
    echo 'This is not a symbolic link.';
}
?>

Output:

The physical address of the symbolic link is: test.txt

Explanation:

As “test” is symbolic link, the is_link() function returns TRUE and the program enter into if condition. The readlink() function at line 3 gets the physical path of the symbolic link (test.txt) and the echo prints it in the next line (line 4).

Best Practices on readlink() Function:

If it is not a symbolic link, the function returns an error. So, before running this function, check whether the symbolic link is a real symbolic link by the is_link() function. Check example 2.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP readlink() Function

When you work with files and folders in your web application and you want to instantly access files and folders, you’ll use symbolic links. And, you’ll also need to know the physical address of the symbolic link. This readlink() function helps you to know this which is a built-in PHP filesystem function.

Reference:

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