【问题标题】:Dynamically finding paths, is there a better way?动态寻找路径,有没有更好的方法?
【发布时间】:2010-11-19 13:04:16
【问题描述】:

我希望能够移动我的代码并能够发现路径以影响某些变量的值。这将放置在初始化变量的页面中。

这是我想出的:

$path_array = explode('/', $_SERVER['SCRIPT_FILENAME']);

$out = "";
// -3 represents the number of folders and files to go back to reach the wanted path

for($i=0; $i < count($path_array) - 3; $i++){
    $out .= $path_array[$i].'/';
}

然后,例如,我可以执行以下操作:

$dyn_path_1 = $out . 'folder1/';
$dyn_path_2 = $out . 'folder2/something_else/';
$dyn_path_3 = $out . 'folder3/';

是否有一些我可能会丢失的内置函数会使其过时?

ps:这将使我们能够拥有多个工作代码副本,而无需在签出代码时担心这些变量。

编辑#1:

变量文件路径:root/folderA/folderB/var.php

在 var.php 中,我必须回到根目录,这取决于方法,需要 2-3 步。我想知道是否有可能做这样的事情:

echo some_function("../../file_I_know.php");

可以返回:C:/root/

【问题讨论】:

    标签: php path


    【解决方案1】:

    看看 PHP 的“魔术常量”定义,大多数人使用 dirname(FILE) 来获取最初执行脚本的目录,将其绑定到常量并使用它作为所有其他目录引用的基础。从而使您的脚本位置独立。

    这是我常用的:

    if (!defined('SITE_BASE_PATH')) {
      $baseDir = dirname(__FILE__); // Get directory of THIS file
      $baseDir = str_replace("\\", "/", $baseDir); // Replace backslashes with forward incase we're in Windows
      $baseDir = realpath($baseDir); // Convert relative path to real path (no '..' etc)
      $baseDir .= "/"; // Add trailing slash - so that we can append filenames directly
      define('SITE_BASE_PATH', $baseDir); // define the constant
    }
    

    或者简称:

    define(SITE_BASE_PATH, realpath(str_replace("\\", "/", dirname(__FILE__))) . '/');
    

    有关详细信息,请参阅以下帮助: http://php.net/manual/en/language.constants.predefined.php

    【讨论】:

    • 这个怎么样:dirname(realpath("../../known_file.txt"));
    • @TekiusFanatikus 是的,这会起作用,但这取决于文件保留其相对位置和名称,而上述定义没有依赖关系。
    • 同意并注明。这是我想我最终会使用的解决方案: dirname(str_replace("\\", "/", realpath("../../known_file.txt")))... @All:谢谢所有的帮助!
    【解决方案2】:

    嘿,您可能想试试__FILE__,这是您所在文件的绝对路径。 dirname(__FILE__) 可能正是您所需要的。

    【讨论】:

    • 它是__FILE__。修正了你的答案。
    【解决方案3】:

    我认为这是一种最可靠的方式(在 index.php 中):

    对于公共目录使用这个: realpath (dirname (__FILE__))

    对于应用程序基础目录: realpath (dirname (__FILE__). "/../")

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多