📅  最后修改于: 2023-12-03 14:45:18.506000             🧑  作者: Mango
The realpath()
function in PHP is used to retrieve the resolved absolute path of a specified file or directory. It returns the canonicalized absolute pathname on success, or false
on failure.
realpath($path)
$path
: The path to the file or directory you want to retrieve the absolute path for.false
.$file = 'example.txt';
$absolutePath = realpath($file);
if ($absolutePath !== false) {
echo "The absolute path for $file is: $absolutePath";
} else {
echo "Failed to get the absolute path for $file.";
}
$directory = '/path/to/directory';
$absolutePath = realpath($directory);
if ($absolutePath !== false) {
echo "The absolute path for $directory is: $absolutePath";
} else {
echo "Failed to get the absolute path for $directory.";
}
In example 1, we provide the name of a file (example.txt
) to the realpath()
function. It returns the absolute path of the file if it exists, or false
otherwise. We then check if the returned value is not false
and display the absolute path accordingly.
In example 2, we provide the path of a directory (/path/to/directory
) to the realpath()
function. It resolves and returns the absolute path of the directory if it exists, or false
otherwise. We then check if the returned value is not false
and display the absolute path accordingly.
realpath()
function should be used with caution, especially when dealing with user-provided paths. It performs filesystem operations, so it can be affected by symbolic links, permissions, and other factors.file_exists()
function instead of realpath()
.