Php 动态查找路径,有更好的方法吗?
我希望能够移动我的代码,并能够发现路径,以便影响某些变量的值。这将被放置在初始化变量的页面中 以下是我的想法:Php 动态查找路径,有更好的方法吗?,php,path,Php,Path,我希望能够移动我的代码,并能够发现路径,以便影响某些变量的值。这将被放置在初始化变量的页面中 以下是我的想法: $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) -
$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].'/';
}
是否有我可能缺少的内置函数会使其过时
ps:这将使我们能够拥有代码的多个工作副本,而不必在签出代码时担心这些变量
编辑1:
变量文件路径:root/folderA/folderB/var.php
在var.php中,我必须回到根目录,这是2-3个步骤,具体取决于方法。我想知道是否有可能这样做:
echo some_function("../../file_I_know.php");
它可能会返回:C:/root/嘿,您可能想尝试使用文件,它是您所在文件的绝对路径。而dirnameFILE可能正是您所需要的。看看PHP的神奇常量定义,大多数人使用dirnameFILE来获取最初执行脚本的目录,将其绑定到一个常量,并将其用作所有其他目录引用的基础。从而使脚本位置独立 这是我通常使用的:
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__))) . '/');
有关详细信息,请参阅以下帮助:
我认为这是index.php中最能证明boollet的方法: 对于公共目录,请使用以下命令: realpath dirname\uu文件__ 对于应用程序基目录: realpath目录名uuuu文件uuuu//
希望有帮助。这是一个文件。修正了你的答案。这个怎么样:dirnamerealpath.././known_file.txt@TekiusFanatikus是的,这将起作用,但这取决于文件是否保留其相对位置和名称,而上述定义没有相关性。同意并注意到。这就是我想最终使用的解决方案:dirnamestr_replace\\,/,realpath.././known_file.txt@谢谢你的帮助!
define(SITE_BASE_PATH, realpath(str_replace("\\", "/", dirname(__FILE__))) . '/');