php 获取PHP项目的根目录路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8668776/
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-26 05:13:33  来源:igfitidea点击:

Get Root Directory Path of a PHP project

php

提问by Nalaka526

I have this folder structure in my PHP project. (this is as shown in eclips)

我的 PHP 项目中有这个文件夹结构。(这如 eclips 所示)

-MySystem
    +Code
    +Data_Access
    -Public_HTML
        +css
        +js
        +Templates
    -resources

When I try this code

当我尝试此代码时

echo $_SERVER['DOCUMENT_ROOT']

output is

输出是

D:/workspace

D:/工作区

How can I get the path to RootDirectory of the system (MySystem), without hardcoding the Folder Name?

如何在MySystem不硬编码文件夹名称的情况下获取系统 ( ) RootDirectory 的路径?

回答by Prasad Rajapaksha

For PHP >= 5.3.0try

对于PHP >= 5.3.0试试

PHP magic constants.

PHP魔法常量

__DIR__

And make your path relative.

并使您的路径相对。

For PHP < 5.3.0try

对于PHP < 5.3.0尝试

dirname(__FILE__)

回答by Armin

When you say that

当你这么说

$_SERVER['DOCUMENT_ROOT']

contains this path:

包含此路径:

D:/workspace

Then D:is what you are looking for, isn't it? In that case you could explode the string by slashes and return the first one:

D:就是你要找的,不是吗?在这种情况下,您可以通过斜线分解字符串并返回第一个:

$pathInPieces = explode('/', $_SERVER['DOCUMENT_ROOT']);
echo $pathInPieces[0];

This will output the server's root directory.

这将输出服务器的根目录。

Update:When you use the constant DIRECTORY_SEPARATORinstead of the hardcoded slash ('/') this code is also working under Windows.

更新:当您使用常量DIRECTORY_SEPARATOR而不是硬编码的斜杠 ( '/') 时,此代码也适用于 Windows。

Update 2:The $_SERVERglobal variable is not always available. On command line (cli) for example. So you should use __DIR__instead of $_SERVER['DOCUMENT_ROOT']. __DIR__returns the path of the php file itself.

更新2:$_SERVER全局变量并不总是可用的。例如在命令行(cli)上。所以你应该使用__DIR__而不是$_SERVER['DOCUMENT_ROOT']. __DIR__返回 php 文件本身的路径。

回答by dkinzer

use the PHP function:

使用 PHP 函数:

getcwd()

getcwd()

Gets the current working directory.

获取当前工作目录。

回答by Hexodus

I want to point to the way Wordpress handles this:

我想指出 Wordpress 处理此问题的方式:

define( 'ABSPATH', dirname(dirname(__FILE__)) . '/' );

As Wordpress is very heavy used all over the web and also works fine locally I have much trust in this method.

由于 Wordpress 在整个网络上使用非常频繁,并且在本地也能正常工作,因此我非常信任这种方法。

回答by This_is_me

you can try: $_SERVER['PATH_TRANSLATED']

你可以试试: $_SERVER['PATH_TRANSLATED']

quote:

引用:

Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping. Note: As of PHP 4.3.2, PATH_TRANSLATEDis no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAMEserver variable when it's not populated by Apache.
This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFOis defined. Apache 2 users may use AcceptPathInfo = Oninside httpd.confto define PATH_INFO

在服务器完成任何虚拟到真实映射之后,基于文件系统(不是文档根目录)的当前脚本的路径。注意:从 PHP 4.3.2 开始,PATH_TRANSLATED与 Apache 1 中的情况相比,不再在 Apache 2 SAPI 下隐式设置,SCRIPT_FILENAME当它没有被 Apache 填充时,它被设置为与服务器变量相同的值。
进行此更改是为了符合 CGI 规范,即 PATH_TRANSLATED 仅在PATH_INFO定义时才存在。Apache 2 用户可以使用AcceptPathInfo = Oninsidehttpd.conf定义PATH_INFO

source: php.net/manual

来源: php.net/手册

回答by Waqar Alamgir

echo $pathInPieces = explode(DIRECTORY_SEPARATOR , __FILE__);
echo $pathInPieces[0].DIRECTORY_SEPARATOR;

回答by Mike Q

Summary

概括

This example assumes you always know where the apache root folder is '/var/www/' and you are trying to find the next folder path (e.g. '/var/www/my_website_folder'). Also this works from a script or the web browser which is why there is additional code.

此示例假设您始终知道 apache 根文件夹在哪里“/var/www/”,并且您正在尝试查找下一个文件夹路径(例如“/var/www/my_website_folder”)。这也适用于脚本或 Web 浏览器,这就是为什么有附加代码的原因。

Code PHP7

代码 PHP7

function getHtmlRootFolder(string $root = '/var/www/') {

    // -- try to use DOCUMENT_ROOT first --
    $ret = str_replace(' ', '', $_SERVER['DOCUMENT_ROOT']);
    $ret = rtrim($ret, '/') . '/';

    // -- if doesn't contain root path, find using this file's loc. path --
    if (!preg_match("#".$root."#", $ret)) {
      $root = rtrim($root, '/') . '/';
      $root_arr = explode("/", $root);
      $pwd_arr = explode("/", getcwd());
      $ret = $root . $pwd_arr[count($root_arr) - 1];
    }

    return (preg_match("#".$root."#", $ret)) ? rtrim($ret, '/') . '/' : null;
}

Example

例子

echo getHtmlRootFolder();

Output:

输出:

/var/www/somedir/

Details:

细节:

Basically first tries to get DOCUMENT_ROOT if it contains '/var/www/' then use it, else get the current dir (which much exist inside the project) and gets the next path value based on count of the $root path. Note: added rtrim statements to ensure the path returns ending with a '/' in all cases . It doesn't check for it requiring to be larger than /var/www/ it can also return /var/www/ as a possible response.

基本上首先尝试获取 DOCUMENT_ROOT 如果它包含 '/var/www/' 然后使用它,否则获取当前目录(项目中存在很多)并根据 $root 路径的计数获取下一个路径值。注意:添加了 rtrim 语句以确保路径在所有情况下都返回以“/”结尾。它不会检查它是否需要大于 /var/www/ 它也可以返回 /var/www/ 作为可能的响应。