PHP的realpath是否执行磁盘访问

时间:2014-03-03 17:22:51

标签: php disk realpath

我相信PHP的realpath函数执行磁盘访问,因为它需要检查当前目录。但是,我想确认这是正确的。

那么,PHP的realpath是否会执行磁盘访问? IE浏览器。它是否对文件系统磁盘执行某种读/写操作/执行硬盘操作?

2 个答案:

答案 0 :(得分:0)

是的确如此!

  

realpath()在失败时返回FALSE,例如如果文件不存在。

realpath执行路径规范化 a file_exists

作为奖励,我将为您提供一项功能,以便在没有磁盘访问的情况下获得类似的功能。

/**
 * This function is a proper replacement for realpath
 * It will _only_ normalize the path and resolve indirections (.. and .)
 * Normalization includes:
 * - directory separator is always /
 * - there is never a trailing directory separator
 * - handles: http, https, ftp, ftps, file prefixes
 * @param  $path
 * @return string normalized path
 */
function normalize_path($path) {

    $allowed_prefixes = array("http://", "https://", "ftp://", "ftps://", "file://");

    foreach ($allowed_prefixes as $prefix) {
        $length = strlen($prefix);
        if ($prefix === substr($path, 0, $length)) {
            return $prefix . normalize_path(substr($path, $length));
        }
    }

    $parts = preg_split(":[\\\/]:", $path); // split on known directory separators

    // remove empty and 'current' paths (./)
    for ($i = 0; $i < count($parts); $i += 1) {
        if ($parts[$i] === ".") {
            unset($parts[$i]);
            $parts = array_values($parts);
            $i -= 1;
        }
        if ($i > 0 && $parts[$i] === "") {  // remove empty parts
            unset($parts[$i]);
            $parts = array_values($parts);
            $i -= 1;
        }
    }
    // resolve relative parts, this double loop required for the case: "abc//..//def", it should yield "def", not "/def"
    for ($i = 0; $i < count($parts); $i += 1) {
        if ($parts[$i] === "..") {          // resolve
            if ($i === 0) {
                throw new Exception("Cannot resolve path, path seems invalid: `" . $path . "`");
            }
            unset($parts[$i - 1]);
            unset($parts[$i]);
            $parts = array_values($parts);
            $i -= 2;
        }
    }
    return implode("/", $parts);
}

答案 1 :(得分:0)

是PHP的realpath函数执行磁盘访问