Find paths dynamically, is there a better way?

I want to be able to move my code and be able to discover a path in order to influence the value of certain variables. This will be placed on the page where the variables are initialized.

Here is what I came up with:

$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].'/'; } 

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 any built-in functions that I could lose that would make this obsolete?

ps: this will allow us to have several working copies of the code without worrying about these variables whenever we check the code.

Edit # 1:

Variable file path: root / folderA / folderB / var.php

Inside var.php, I need to go back to the root, which is 2-3 steps depending on the method. I wonder if it is possible to do something like this:

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

which could return: C: / root /

0
source share
3 answers

Take a look at the definition of "magic constants" for PHP, most people use dirname ( FILE ) to get the directory of the script that is initially running, bind it to a constant, and use this as a base for all other directory links. So your script position is 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__))) . '/'); 

For more information, see the following help: http://php.net/manual/en/language.constants.predefined.php

0
source

Hey, you can try __FILE__ , which is the absolute path for the file you are in. And dirname(__FILE__) may be exactly what you need.

0
source

I think this is the most reliable way (in index.php):

for public registry use this: realpath (dirname (__FILE__))

for the application database: realpath (dirname (__FILE__). "/../")

Hope this helps.

0
source

Source: https://habr.com/ru/post/1440641/


All Articles