Dynamically finding paths, is there a better way?
I want to be able to move my code around and be able to discover the path in order to affect the value of certain variables. This will be placed in the page where the variables get initialized.
Here's what I came up with:
$path_array = explode('/', $_SERVER['SCRIPT_FILENAME']);
$out开发者_JAVA技巧 = "";
// -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].'/';
}
Then, as an example, I can do the following:
$dyn_path_1 = $out . 'folder1/';
$dyn_path_2 = $out . 'folder2/something_else/';
$dyn_path_3 = $out . 'folder3/';
Are there built in functions that I could be missing that would make this obsolete?
ps: this would enable us to have multiple working copies of code without having to worry about these variables whenever we checkout the code.
Edit #1:
Path of variable file: root/folderA/folderB/var.php
Within var.php, I have to go back down to root which is 2-3 steps depending on the method. I wonder if it would be possible doing something like this:
echo some_function("../../file_I_know.php");
Which could return: C:/root/
Take a look at the "magic constants" definitions for PHP, most people use dirname(FILE) in order to get the directory of the initially executing script, bind that to a constant and use that as the base for all other directory references. Thus making your script position independent.
This is what I usually use:
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
}
Or in short form:
define(SITE_BASE_PATH, realpath(str_replace("\\", "/", dirname(__FILE__))) . '/');
See the following help for more information: http://php.net/manual/en/language.constants.predefined.php
hey, you might want to try __FILE__
, which is the absolute path of the file you're on. And dirname(__FILE__)
might be just what you need.
I think this is a most boollet-proof way (in index.php) :
for public dir use this:
realpath (dirname (__FILE__))
for application base dir:
realpath (dirname (__FILE__). "/../")
Hope that helps.
精彩评论