【问题标题】:How to get rootpath when the defines are set in a subdirectory?在子目录中设置定义时如何获取根路径?
【发布时间】:2013-03-21 18:13:25
【问题描述】:

当定义位于子目录中时,获取实际(完整)根路径的可靠方法?考虑:

E:\web\sites\name\index.php
E:\web\sites\name\res\defines.php
E:\web\sites\name\res\another.php
E:\web\sites\name\classes\class-example.php

E:\web\ 是本地主机,E:\web\sites\name 是网站的预期根目录。

$file = ROOTPATH."\data\feature\file.txt";的方式定义=E:\web\sites\name\data\feature\file.txt的示例路径

我不使用相对路径的原因是因为我想在classes\class-example.phpres\another.php 中传递路径,而不对同一个目标使用两个常量。

那么,在 res\defines.php 中,有什么方法可以让根路径指向 E:\web\sites\name\?当网站在服务器上时,同一个ROOTPATH应该指向http://www.example.com/

这是我在 define.php 位于 res\defines.php 时得到的结果:

// Outputs: E:\web\sites\name\res
echo __DIR__;

// Outputs: E:\web\sites\name\res
echo realpath(__DIR__);

// Outputs: sites\name\res\another.php
echo $_SERVER['REQUEST_URI']

// Outputs: E:\web
echo $_SERVER['DOCUMENT_ROOT'];

// Outputs: sites\name\res\another.php
echo $_SERVER['SCRIPT_NAME'];

// Outputs: E:\web\sites\name\res\defines.php
echo __FILE__;

// Outputs: sites\name\res\another.php
echo $_SERVER['PHP_SELF'];

【问题讨论】:

    标签: php directory filepath


    【解决方案1】:

    诀窍是使用:dirname(__DIR__) (PHP >= 5.3.0)。

    // Outputs: E:\web\sites\name
    echo dirname(__DIR__);
    

    请注意,有些问题有点像这样,但我检查过的问题都没有关于dirname(__DIR__)的信息;他们都只提到了dirname(__FILE__),它输出与dirname(__DIR__)相同的东西-__FILE__版本输出E:\web\sites\name\res

    希望此信息可以帮助其他在子目录方面遇到类似问题的人:)

    如果有人也有旧 PHP 版本的解决方案,会很有趣,以防有人使用...

    【讨论】:

      猜你喜欢
      • 2014-08-29
      • 2022-12-13
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 2021-12-12
      • 1970-01-01
      • 2021-04-08
      相关资源
      最近更新 更多