无论从 PHP 中的哪个位置获取相对目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2090723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:58:23  来源:igfitidea点击:

How to get the relative directory no matter from where it's included in PHP?

phppath

提问by user198729

If it's Path_To_DocumentRoot/a/b/c.php,should always be /a/b.

如果是Path_To_DocumentRoot/a/b/c.php,应该总是/a/b

I use this:

我用这个:

dirname($_SERVER["PHP_SELF"])

But it won't work when it's included by another file in a different directory.

但是当它被另一个目录中的另一个文件包含时它不起作用。

EDIT

编辑

I need a relative path to document root .It's used in web application.

我需要一个文档 root 的相对路径。它在 web 应用程序中使用。

I find there is another question with the same problem,but no accepted answer yet.

我发现还有另一个问题有同样的问题,但还没有被接受的答案。

PHP - Convert File system path to URL

PHP - 将文件系统路径转换为 ​​URL

回答by Alix Axel

Do you have access to $_SERVER['SCRIPT_NAME']? If you do, doing:

你有访问权限$_SERVER['SCRIPT_NAME']吗?如果这样做,请执行以下操作:

dirname($_SERVER['SCRIPT_NAME']);

Should work. Otherwise do this:

应该管用。否则这样做:

In PHP < 5.3:

在 PHP < 5.3 中:

substr(dirname(__FILE__), strlen($_SERVER['DOCUMENT_ROOT']));

Or PHP >= 5.3:

或 PHP >= 5.3:

substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT']));


You might need to realpath()and str_replace()all \to /to make it fully portable, like this:

您可能需要realpath()str_replace()所有\才能/使其完全可移植,如下所示:

substr(str_replace('\', '/', realpath(dirname(__FILE__))), strlen(str_replace('\', '/', realpath($_SERVER['DOCUMENT_ROOT']))));

回答by Lukman

PHP < 5.3:

PHP < 5.3:

dirname(__FILE__)

dirname(__FILE__)

PHP >= 5.3:

PHP >= 5.3:

__DIR__

__DIR__

EDIT:

编辑:

Here is the code to get path of included file relative to the path of running php file:

这是获取包含文件相对于运行 php 文件路径的路径的代码:

    $thispath = explode('\', str_replace('/','\', dirname(__FILE__)));
    $rootpath = explode('\', str_replace('/','\', dirname($_SERVER["SCRIPT_FILENAME"])));
    $relpath = array();
    $dotted = 0;
    for ($i = 0; $i < count($rootpath); $i++) {
        if ($i >= count($thispath)) {
            $dotted++;
        }
        elseif ($thispath[$i] != $rootpath[$i]) {
            $relpath[] = $thispath[$i]; 
            $dotted++;
        }
    }
    print str_repeat('../', $dotted) . implode('/', array_merge($relpath, array_slice($thispath, count($rootpath))));

回答by adamfowlerphoto

I know this is an old question but the solutions suggested using DOCUMENT_ROOT assume the web folder structure reflects the server folder structure. I have a situation where this isn't the case. My solution is as follows. You can work out how a server address maps to a web address if you have an example from the same mapped area folders. As long as the root php file that included this file is in the same mapped area you have an example.

我知道这是一个老问题,但建议使用 DOCUMENT_ROOT 的解决方案假设 Web 文件夹结构反映了服务器文件夹结构。我的情况并非如此。我的解决方法如下。如果您有来自相同映射区域文件夹的示例,则可以计算服务器地址如何映射到 Web 地址。只要包含此文件的根 php 文件位于同一映射区域,您就有一个示例。

$_SERVER['SCRIPT_FILENAME'] is the server address of this file and $_SERVER['PHP_SELF'] is the web relative version. Given these two you can work out what the web relative version of your file is from its server address (__FILE__) as follows.

$_SERVER['SCRIPT_FILENAME'] 是该文件的服务器地址,$_SERVER['PHP_SELF'] 是网络相关版本。鉴于这两个,您可以从其服务器地址 (__FILE__) 计算出您的文件的网络相关版本,如下所示。

function getCurrentFileUrl() {
    $file = __FILE__;
    $script = $_SERVER['SCRIPT_FILENAME'];
    $phpself = $_SERVER['PHP_SELF'];

    // find end of section of $file which is common to $script
    $i = 0;
    while($file[$i] == $script[$i]) {
        $i++;
    }
    // remove end section of $phpself that is the equivalent to the section of $script not included in $file. 
    $phpself = substr($phpself, 0, strlen($phpself)-(strlen($script)-$i));
    // append end section of $file onto result
    $phpself .= substr($file, $i, strlen($file)-$i);

    // complete address 
    return $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$phpself;
}

回答by inquam

Here's a general purpose function to get the relative path between two paths.

这是一个通用函数,用于获取两条路径之间的相对路径。

/**
 * Return relative path between two sources
 * @param $from
 * @param $to
 * @param string $separator
 * @return string
 */
function relativePath($from, $to, $separator = DIRECTORY_SEPARATOR)
{
    $from   = str_replace(array('/', '\'), $separator, $from);
    $to     = str_replace(array('/', '\'), $separator, $to);

    $arFrom = explode($separator, rtrim($from, $separator));
    $arTo = explode($separator, rtrim($to, $separator));
    while(count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0]))
    {
        array_shift($arFrom);
        array_shift($arTo);
    }

    return str_pad("", count($arFrom) * 3, '..'.$separator).implode($separator, $arTo);
}

Examples

例子

relativePath('c:\temp\foo\bar', 'c:\temp');              // Result: ../../
relativePath('c:\temp\foo\bar', 'c:\');                 // Result: ../../../
relativePath('c:\temp\foo\bar', 'c:\temp\foo\bar\lala'); // Result: lala

回答by Artur St?pień

I had to create something to what you need so here is the result. By giving a base directory you receive a relative path to a file starting from base directory. Function is pretty fast, 100,000 checks took 0.64s. on my server. And it works for both directories and files. It is linux compatible. Don't even try it on windows :)

我必须根据您的需要创建一些东西,所以这就是结果。通过提供基本目录,您会收到从基本目录开始的文件的相对路径。功能相当快,100,000 次检查需要 0.64 秒。在我的服务器上。它适用于目录和文件。它是Linux兼容的。甚至不要在 Windows 上尝试它:)

     /**
     * Return a relative path to a file or directory using base directory. 
     * When you set $base to /website and $path to /website/store/library.php
     * this function will return /store/library.php
     * 
     * Remember: All paths have to start from "/" or "\" this is not Windows compatible.
     * 
     * @param   String   $base   A base path used to construct relative path. For example /website
     * @param   String   $path   A full path to file or directory used to construct relative path. For example /website/store/library.php
     * 
     * @return  String
     */
    function getRelativePath($base, $path) {
        // Detect directory separator
        $separator = substr($base, 0, 1);
        $base = array_slice(explode($separator, rtrim($base,$separator)),1);
        $path = array_slice(explode($separator, rtrim($path,$separator)),1);

        return $separator.implode($separator, array_slice($path, count($base)));
    }

Usage

用法

You need to get relative path to file /var/www/example.com/media/test.jpgYour base path is /var/www/example.com

您需要获取文件的相对路径/var/www/example.com/media/test.jpg您的基本路径是/var/www/example.com

Use the function like this:

像这样使用函数:

$relative = getRelativePath('/var/www/example.com','/var/www/example.com/media/test.jpg');

Function will return /media/test.jpg.

函数将返回/media/test.jpg

If you need only the /mediapart without a file use it like this:

如果您只需要/media没有文件的部分,请像这样使用它:

$relative = dirname(getRelativePath('/var/www/example.com','/var/www/example.com/media/test.jpg'));