获取文件目录的URL路径(PHP)

问题描述 投票:2回答:4

你好 我有一个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 apache
4个回答
6
投票

这怎么对我有用:)

<?php 
    $path = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
    $path .=$_SERVER["SERVER_NAME"]. dirname($_SERVER["PHP_SELF"]);        
    echo $path;
?>

2
投票

在您包含的文件中:

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

2
投票

我自己想通了:

$realpath    = str_replace('\\', '/', dirname(__FILE__));
$whatIwanted = substr_replace(str_replace($_SERVER['DOCUMENT_ROOT'], '', $realpath), "", -6);

我们去了:)感谢帮助人员。


1
投票

这个步骤是:

  1. 使用dirname(__FILE__)获取包含文件的文件夹。
  2. 使用$_SERVER['DOCUMENT_ROOT']获取服务器根目录
  3. 从include文件夹中删除文档根目录以获取相对包含文件夹
  4. 获取服务器URL
  5. 将相对包含文件夹附加到服务器URL
© www.soinside.com 2019 - 2024. All rights reserved.