📜  PHP | realpath()函数(1)

📅  最后修改于: 2023-12-03 14:45:18.506000             🧑  作者: Mango

PHP | realpath()函数

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.

Syntax
realpath($path)
Parameters
  • $path: The path to the file or directory you want to retrieve the absolute path for.
Return Value
  • The function returns the resolved absolute path as a string on success.
  • If the specified path does not exist or an error occurs, it returns false.
Examples

Example 1: Using realpath() for a File

$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.";
}

Example 2: Using realpath() for a Directory

$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.";
}
Explanation

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.

Notes
  • The 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.
  • The returned absolute path may have symbolic links resolved, trailing slashes eliminated, and other canonicalized representation modifications.
  • If you want to check if a file or directory exists, it is better to use the file_exists() function instead of realpath().