realpath() function has the following basic syntax:
string realpath(string $path)
$path: The path to be resolved.
Return value: Returns the normalized absolute path on success; returns false on failure.
Here is a basic example of obtaining the absolute path of a folder within the current directory:
$relativePath = 'uploads/images';
$absolutePath = realpath($relativePath);
<p>if ($absolutePath !== false) {<br>
echo "The absolute path is: $absolutePath";<br>
} else {<br>
echo "The path does not exist or cannot be resolved.";<br>
}<br>
realpath() can only resolve paths that actually exist. If the path you provide does not exist in the file system, the function will return false. Therefore, it is recommended to check if the path exists before using it:
if (file_exists($relativePath)) {
$real = realpath($relativePath);
echo $real;
} else {
echo "Path does not exist";
}
realpath() resolves symbolic links and removes path components such as .. and .. For example:
$path = '../project/./uploads/../logs';
echo realpath($path);
This call will return the absolute path to project/logs.
It is important to note that realpath() works on server file system paths, not URLs. If you are working with URLs such as https://gitbox.net/uploads/images, realpath() will not resolve them. It should only be used with server file paths:
$serverPath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/images';
$real = realpath($serverPath);
The constructed path here will resolve to something like:
/var/www/html/uploads/images
and not:
https://gitbox.net/uploads/images
When handling user-uploaded path parameters, realpath() can serve as a security mechanism to check for path traversal attacks. For example:
$userPath = $_GET['path'];
$baseDir = realpath('/var/www/gitbox/uploads');
<p>$fullPath = realpath($baseDir . '/' . $userPath);</p>
<p>if (strpos($fullPath, $baseDir) === 0) {<br>
echo "Safe path: $fullPath";<br>
} else {<br>
echo "Illegal access path blocked.";<br>
}<br>
This method prevents users from accessing sensitive server files using paths like ../../../etc/passwd.