Find current directory level using PHP

I need a require_once file, which is located in the root directory of my sites. The problem is that I will not always know how many levels of the root directory are located where the current current script is running. So I need to find out how many directory levels I need to find in the require_once file.

Sometimes it can be:

require_once '../../file.php'; 

And sometimes it can be:

 require_once '../file.php'; 

Or any other number of directory levels.

How can I calculate how much "../" I need to get to the root directory from anywhere in the subdirectory?

+4
source share
7 answers

Create the SITE_ROOT constant in index.php and use it wherever you need to specify the path, for example:

 require_once SITE_ROOT . '/path/from/siteroot/to/file.ext'; 
+5
source

Here is a simple way that I found out:

 // get current file location $pieces = explode("/", $_SERVER['PHP_SELF']); // subtract 1 for left / and 1 for current file $loop = count($pieces) - 2; // loop until to root directory for ($i=0; $i<$loop; $i++) { $up_dirs .= "../"; } 

Probably not as effective as some other suggestions. But I tested it and it works.

+3
source

You can use dirname(__FILE__) to make sure it is always in the directory of your include file

+1
source

You can get the root of the site document using $_SERVER['DOCUMENT_ROOT'] and assuming that nothing in the code has changed the current working directory, you can get it using getcwd() . With these two ways, use the code for this comment to calculate the difference.

+1
source

There are several options. But you will need to decide what suits your case:

  • spl_autoload
  • set_include_path
  • Relative path traversal using include(dirname(__FILE__)."/file.php");
  • Server-related paths using include("$_SERVER[DOCUMENT_ROOT]/file.php");

For applications, the predefined root directory is the path. For libraries, this is also the preferred approach.

+1
source

You can specify a path from above, for example

 "/my/user/dir/file.php" 
0
source

getcwd() will return the current working line of the directory.

0
source

All Articles