php

How to Use realpath() Function in PHP

PHP is a scripting language used to build interactive websites and applications. It has various built-in functions that help developers create efficient web applications. The realpath() function is a built-in function of PHP that is used for obtaining the real or absolute path of a file or a directory. It returns all the symbolic links and returns the absolute path.

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:

realpath(path)

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.

<?php
echo realpath("myfile.txt");
?>

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:

<?php
$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.

About the author

Zainab Rehman

I'm an author by profession. My interest in the internet world motivates me to write for Linux Hint and I'm here to share my knowledge with others.