我相信 PHP 的 realpath 函数会执行磁盘访问,因为它需要检查当前目录。但是,我想确认这是正确的。
那么,PHP 的 realpath 是否执行磁盘访问?IE。它是否对文件系统磁盘执行某种读/写操作/执行硬盘操作?
是的,它确实!
realpath () 在失败时返回 FALSE,例如如果文件不存在。
realpath
进行路径规范化和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);
}
是 PHP 的 realpath 函数执行磁盘访问