function findRoot() {
return(substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1));
}
函数返回服务器的绝对路径;然而,我不确定它是如何工作的。在使用任何代码之前,我喜欢确切地了解它是如何工作的,这样我就可以更好地理解和实现脚本。
谁能解释一下它是怎么工作的?我以前使用过substr();然而,从来没有任何事情达到这种程度。
也欢迎对脚本的改进提出建议。
$_SERVER["SCRIPT_NAME"]
包含脚本相对于根目录的路径。服务器像php relative/path.php
一样从服务器根目录调用PHP;这是带有/
的脚本的名称;基本上,带有此URL的链接指向同一页面。
$_SERVER["SCRIPT_FILENAME"]
包含脚本的绝对路径。这是由PHP解决的。
stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1
相对路径在绝对路径中的位置。从绝对文件名中取出这么多字符将不包括末尾的/
,因此添加1。
substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1))
绝对文件名在相对路径之前的部分;在上一步中从绝对文件名中计算出的字符数量。这必须是根,因为相对文件名是相对于服务器根的。
通过逐行限制一个操作,使代码更容易理解。下面是几乎相同的函数,有额外的细节和回声:
function find_absolute_path() {
$strScriptFilename = $_SERVER["SCRIPT_FILENAME"];
$strScriptName = $_SERVER["SCRIPT_NAME"];
// stripos — Find the position of the first occurrence of a case-insensitive substring in a string.
// int stripos ( string $haystack , string $needle [, int $offset = 0 ] )
$intPositionOfName = stripos($strScriptFilename, $strScriptName);
// substr — Return part of a string.
// string substr ( string $string , int $start [, int $length ] )
$strWwwPathWithoutName = substr($strScriptFilename, 0,($intPositionOfName + 1));
echo "strScriptFilename: " . $strScriptFilename . "<br/>";
echo "strScriptName: " . $strScriptName . "<br/>";
echo "intPositionOfName: " . $intPositionOfName . "<br/>";
echo "strWwwPathWithoutName: " . $strWwwPathWithoutName . "<br/>";
return $strWwwPathWithoutName;
} // find_absolute_path
$strAbsolutePath = find_absolute_path();
echo "strWebPath: " . $strAbsolutePath;
你会注意到脚本是如何从绝对路径中删除$_SERVER["SCRIPT_FILENAME"],将路径留给web服务器的。