你好 我有一个php文件,比如localhost / foo / foo / bar.php 其中包含localhost / foo / included.php中的文件 我需要能够将“localhost / foo /”作为include.php中的字符串 如果,而不是localhost / foo / foo / bar.php,它是localhost / big / burpy / lolz / here.php(仍然包括included.php)我还需要得到“localhost / foo /” 所以,我需要包含文件的路径,而不是客户端请求的路径。
我知道当我看到解决方案时,我会感觉像是一个doofus,但它现在只是逃避了我。请帮忙?谢谢 :)
这怎么对我有用:)
<?php
$path = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
$path .=$_SERVER["SERVER_NAME"]. dirname($_SERVER["PHP_SELF"]);
echo $path;
?>
在您包含的文件中:
$yourdir = dirname(__FILE__);
或者如果您使用的是PHP 5.3.x:
$yourdir = __DIR__;
从中获取文档根目录
// contains the document root, e.g. C:\xampp\htdocs
$docRoot = realpath($_SERVER['DOCUMENT_ROOT']);
// strip drive letter if found
if(strpos($docRoot, ':') === 1) $docRoot = substr($docRoot, 2);
// directory of included file, e.g. C:\xampp\htdocs\include
$dirInclude = realpath(dirname(__FILE__));
// strip drive letter if found
if(strpos($dirInclude, ':') === 1) $dirInclude = substr($dirInclude, 2);
// find the document root
$rootPos = strpos($dirInclude, $docRoot);
// if the path really starts with the document root
if($rootPos === 0){
// example: \xampp\htdocs\include
$visibleDir = substr($rootPos, $);
// convert backslashes to slashes and strip drive letter
$webPath = str_replace('\\', '/', $visibleDir);
// yields: http://localhost/include
echo 'http://localhost' . $webPath;
}
else{
// included file was outside the webroot, nothing to do...
}
我自己想通了:
$realpath = str_replace('\\', '/', dirname(__FILE__));
$whatIwanted = substr_replace(str_replace($_SERVER['DOCUMENT_ROOT'], '', $realpath), "", -6);
我们去了:)感谢帮助人员。
这个步骤是:
dirname(__FILE__)
获取包含文件的文件夹。$_SERVER['DOCUMENT_ROOT']
获取服务器根目录