PHP symlink() Function

What is PHP symlink() Function?

If you want to create a symbolic link of an existing file or folder of your file system, use PHP syslink() function. It is a shortcut to an existing file or directory. You can think of this similar to Windows shortcut.

Mention the targeted file or folder which you want to create symbolic link for and the symbolic name in the function. And, the function creates the symbolic link with that name.

Please note that though the name sounds link but it doesn’t create a link that you can create with HTML link.

Syntax:

symlink(target, link)

Parameters:

The Function has 2 parameters; both are required-

target (Required): it is the targeted file or folder for which you will create symbolic link.

link (Required): it is the name of the symbolic link.

Return Values:

The function returns-

  • TRUE – if the function can create symbolic link and
  • 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 targeted file from the symbolic link (here $link variable).

Example 2:

<?php
$target = 'D:/xampp/htdocs/phpExercise/file/fake.txt';
$link = 'test';
symlink($target, $link);
?>

Output:

Warning: symlink(): No such file or directory in D:\xampp\htdocs\php\symlink.php on line 4

Explanation:

There is no file named fake.txt in the specified path, so the symlink() throws Warning on Windows system.

Practical Usages of symlink() Function:

As the symlink() function creates shortcut for a file or folder of your file system, it allows you to access that file and folder located in different places in your file system easily.

Notes on symlink() Function:

  • On Windows system, symlink() doesn’t work with relative path. Use absolute path of the targeted file or folder.
  • The function works on your server’s file system; it doesn’t work on remote files/folders.
  • If the symbolic name already exists, the function throws a warning.
  • If the targeted file/folder doesn’t exist, the function returns warning on Windows system. Check example 2.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP symlink() Function

When working with files/folders in your PHP applications, you may need to create symbolic link and then you’ll use this symlink() function which is a built-in PHP filesystem function.

Reference:

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