In this tutorial, we will learn the realpath() function, its usage, syntax, and examples in PHP.
realpath() Function in PHP
In PHP, the realpath() function is a handy tool for obtaining the absolute path of a specified file or directory. It provides comprehensive information about the specified file, eliminating the need for additional details to locate it. This function resolves symbolic links and converts relative paths to absolute paths. It is important to know that relative and absolute paths differ in their representations. The file’s location relative to the current directory is a relative path, while an absolute path denotes the file’s path starting from the root.
Syntax
The following is the format of the realpath() function in PHP:
Here, the path is the file or directory whose absolute path needs to be determined. This function returns the absolute path by removing the symbolic links and false on the failure of the function.
How to Use realpath() Function in PHP
Suppose we have created a file with the name myfile.txt in our system, and we want to find the real or absolute path of it using the realpath() function. You can use the following PHP code by replacing the file path accordingly.
Executing the above code will return the path of the file.
Suppose, we change the file name and the file is not present on the system, this function returns an error or false:
For example:
$path = realpath("htdcos/file1.txt");
if ($path === true) {
echo "The file found";
} else {
echo "The file not found";
}
?>
Bottom Line
The realpath() function in PHP plays a crucial role in obtaining the absolute path of a file or directory. It resolves symbolic links and converts relative paths into absolute paths, providing comprehensive information for file management. By understanding the syntax and usage of realpath(), developers can accurately locate files and enhance the efficiency of their PHP applications.