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

PHP Filesystem readlink() Function



The PHP Filesystem readlink() function is used to return the target of a symbolic link, and this function can return the target of a link on success or false on failure. The readlink() function does the same as the readlink C function.

The function fails if the path is not a symlink, except in Windows, which returns the normalized path.

Syntax

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

string readlink ( string $path )

Parameters

Below is the required parameter of the readlink() function −

Sr.No Parameter & Description
1

$path(Required)

It is the file to read.

Return Value

The function readlink() returns the target of a link on success or FALSE on failure.

PHP Version

The readlink() 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 readlink() function is used to read the target of a symbolic link.

<?php
   echo readlink("/PhpProject/testlink");
?>

Output

Here is the outcome of the following code −

/home/user/documents/myfile.txt

Example

Here is the another example to show the usage of readlink() function to handle the errors while using this function.

<?php
   $target = readlink("/PhpProject/testlink");

   if ($target !== false) {
      echo "The symbolic link points to: " . $target;
   } else {
      echo "Failed to read the symbolic link.";
   }
?> 

Output

This will produce the following result −

If the read was successful −

The symbolic link points to: /home/user/myfile.txt

If the read was failed −

Failed to read the symbolic link.

Example

Here is one more example to read the symbolic link to a directory with the help of the readlink() function.

<?php
   // Path to the symbolic link
   $symlink = '/PhpProjects'; 
   $target = readlink($symlink);

   if ($target !== false) {
      echo "The symbolic link points to: " . $target;
   } else {
      echo "Failed to read the symbolic link.";
   }
?> 

Output

This will generate the below output −

The symbolic link points to: /var/www/html

Example

Here is one more example to use readlink() function to read a symbolic link which points to a config file.

<?php
   // Path to the symbolic link
   $symlink = '/home/user/symlink'; 
   $target = readlink($symlink);

   if ($target !== false) {
      echo "The symbolic link points to: " . $target;
   } else {
      echo "Failed to read the symbolic link.";
   }
?> 

Output

This will lead to the following output −

The symbolic link points to: /etc/config/settings.conf

Summary

The readlink() method is a built-in function to return the target of a symbolic link. The above examples shows how this function works with symbolic links found in different directories.

php_function_reference.htm
Advertisements