我希望能够移动我的代码,并能够发现路径,以便影响某些变量的值。这将放在初始化变量的页面中。
这是我想出来的:
$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/
发布于 2010-11-19 21:47:44
看看PHP的“魔术常量”定义,大多数人使用dirname(文件)来获取最初执行的脚本的目录,将其绑定到一个常量,并将其用作所有其他目录引用的基础。从而使您的脚本位置独立。
这是我通常使用的:
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
发布于 2010-11-19 21:30:12
嘿,你可能想试试__FILE__,这是你所在文件的绝对路径。而dirname(__FILE__)可能正是您所需要的。
发布于 2010-11-19 22:23:04
我认为这是一种最简单的方式(在index.php中):
对于公共目录,请使用以下命令:realpath (dirname (__FILE__))
对于应用程序基本目录:realpath (dirname (__FILE__). "/../")
希望这能有所帮助。
https://stackoverflow.com/questions/4225254
复制相似问题