How do i get to the root directory in php?

At this moment, PHP itself does not provide a way to get the project's root directory for sure.

But you can implement a very simple method yourself that will do exactly what you're looking for.

Solution

Create a new file in your project, let say D:/workspace/MySystem/Code/FilesManager.php (use whatever name and path suit you the best). Then, use the following code:

Now you can do this in, let's say D:/workspace/MySystem/Code/a/b/c/Feature.php:

echo FilesManager::rootDirectory();

And the expected result should be:

"D:/workspace/MySystem"

The output will be the same no matter where your "feature" file is located in the project.

Explanation

dirname is used to return the parent directory of the first parameter. We use the magic constant __FILE__ to give it FilesManager.php's path. The second parameter tells how many times to go up in the hierarchy. In this case, we need to do it twice, but it really depends where you put your file in the hierarchy. You can omit the second parameter if you only need to got up once, meaning the file is located in the root. But then, you can return __DIR__ directly instead.

This solution is guaranteed to work, no matter where the root is located on your server. Unless you end up moving the utility class somewhere else in the hierarchy.

Additional note

I'd avoid using DOCUMENT_ROOT for the following reasons (according to this answer):

  • It makes your application dependent on the server.
  • The Apache setup may give an incorrect path to the root directory.

How do i get to the root directory in php?
The PHP root directory can be extracted through PHP built-in functions and constants. Moreover, the stated directory can be changed to your preferred path. So, our expertly written article will educate you about the various simple ways to access your root directory along with changing it.

Continue reading to get the PHP root path printed on your browser window in a few seconds.

Contents

  • Get Root Directory: Use the Super Global Variable
    • – Coding Example for Getting PHP Root Directory With $_SERVER
  • Get Base Directory: Execute the Dirname() Function
    • – Discussing the Levels Parameter in PHP Version 7 and Above
    • – Coding Example for Getting PHP Root Directory by Using Dirname()
  • PHP Root Path: Use Dirname() With __DIR__
    • – Coding Example for Getting PHP Root Path By Using __DIR__
  • How To Get To Root Directory in PHP: Use Chroot()
    • – Coding Example for Using the Chroot() Function
    • – Note:
  • PHP Get Root Directory of Website: Going to the Top
    • – Coding Example for Getting Root Directory of Website
  • PHP Root Directory Path: Comparing the Magical Constants
    • – Coding Example for Comparing the Magical Constants
  • Winding Up

Get Root Directory: Use the Super Global Variable

You might find it hard to believe but the super global variable $_SERVER can help you in finding the PHP root directory path. Certainly, the PHP root path is stored on the “DOCUMENT_ROOT” element of the $_SERVER array. Therefore, accessing the given element will return the parent directory path accurately. Also, it would be best to note that the $DOCUMENT_ROOT element is defined in the server’s configuration file.

– Coding Example for Getting PHP Root Directory With $_SERVER

Suppose your current PHP script is created in the “main” directory, but now, you want to get the base directory. So, you’ll print $_SERVER[“DOCUMENT_ROOT”] to get your required results. What’s more, the output will contain the complete PHP root directory path. Also, you can easily identify the parent directory from the result returned by the $_SERVER[“DOCUMENT_ROOT”].

Please feel free to see how the $_SERVER array helps in your root directory search process:


// getting your current directory
echo getcwd();
// output: C:xampphtdocsmain
// printing the root directory path
echo $_SERVER[“DOCUMENT_ROOT”];
// output: C:xampphtdocs
?>

Get Base Directory: Execute the Dirname() Function

Certainly, you don’t need to worry if your currently installed version of PHP is below 5.3.0 because you can execute the dirname() function. The dirname() function will let you pass the required file or folder path and an optional number of levels. Next, the same function will return the PHP root directory path with maximum accuracy.

Furthermore, its syntax is right here: dirname(path, levels).

– Discussing the Levels Parameter in PHP Version 7 and Above

In PHP version 7 and above, the dirname() function allows you to specify the number of levels while acquiring the PHP root directory. You can pass an integer value that comes above one as the second argument to the dirname() function. For example, if you want to PHP get base directory that is one level above your current directory, then you’ll pass two and so on.

– Coding Example for Getting PHP Root Directory by Using Dirname()

Imagine having a script file saved in the “src” directory that exists in the “MyWebsite” directory with the path: “C:xampphtdocsMyWebsitesrc.” Now, let’s assume you also want to get the base directory that exists three levels above your script file. Here, the simplest way to pass the path of your current file to the dirname() function is by passing the __FILE__ constant to it. Next, you’ll pass three as the number of levels.

Please have a look at this code representation that depicts the stated example in the easiest possible manner so you can use it in your programming practice:


// printing your current directory
echo getcwd();
// output: C:xampphtdocsMyWebsitesrc
// printing the third level root directory path
echo dirname(__FILE__, 3);
// output: C:xampphtdocs
?>

PHP Root Path: Use Dirname() With __DIR__

Are you using a PHP version 5.3.0 and above, and looking for a solution to get the PHP root path? Then do nothing else except for passing the magical constant “__DIR__” to the dirname() function. The given constant will return the path of your current directory and the dirname() function will return the PHP root directory of the same.

– Coding Example for Getting PHP Root Path By Using __DIR__

For instance, let’s discuss a case in which the main directory of your PHP project is “MyProject” and it is saved in the “htdocs” folder located in the xampp folder in C drive. This hypothetical directory consists of two subfolders: “assets” and “images” and your current file “myFile.php” is located in the “assets” folder.

Now, you may want to PHP get base directory path of your current directory. Here, you’ll simply pass the magic constant __DIR__ to the dirname() function to acquire accurate results.

Please feel free to use the short code snippet we have provided for you below that implements the dirname() function with the __DIR__ constant:


// getting the root path of the assets directory
echo dirname(__DIR__);
// output: C:xampphtdocsMyProject
?>

How To Get To Root Directory in PHP: Use Chroot()

So, if you are a user of the BSD or GNU Operating System then here you’ll see how to get to root directory in PHP. You can set the current directory to “/” by implementing the chroot() function either in CGI, CLI, or Embed SAPI. Also, the same function changes the path of the PHP root directory. Hence, the incredible functionality of the chroot() function will amaze you to a great extent.

Undeniably, the given function accepts a directory that apparently changes the PHP root directory of the current process to the same, and makes “/” the current directory.

You will need to use this syntax in any relevant code you are planning to create: chroot(directory).

– Coding Example for Using the Chroot() Function

For example, let’s say you want to change the path of your root directory. Secondly, you also want to get to your root directory. In this case, you’ll use the chroot() function by following the syntax above. Consequently, you’ll have both of your requirements fulfilled.

Here is a code fragment to help you in switching to the root directory easily:


// echo your current directory
echo getcwd();
// output: C:xampphtdocsMyFolder
// using the chroot function
chroot(“/NewFolder/”);
// echo your current directory again
echo getcwd();
// output: /
?>

– Note:

The chroot() function doesn’t work on Windows Operating System while it requires root privileges on the systems stated above.

PHP Get Root Directory of Website: Going to the Top

Do you have a large website directory consisting of various directories, subdirectories, and files? Would you like to see the topmost level of your website directory without jumping through all the layers? Well, you can do this by applying a small trick with the combination of the explode() function and the $_SERVER variable. In the end, you’ll PHP get root directory of website without wasting your time in counting the levels backward.

– Coding Example for Getting Root Directory of Website

For instance, we are creating a hypothetical case in which  your current file “newFile.php” has the path “C:xampphtdocswebsiteassetsmainpagesadmincontactnewFile.php.” But now, you want to access its topmost directory.

In the given scenario, you’ll use the explode function and convert the path returned by the $_SERVER[“DOCUMENT_ROOT”] into an array by using “/” as a separator. Next, you’ll access the first element of the resulting path array to get your PHP root directory.

Please go through the piece of code given below for more assistance:


// converting the root directory path string into an array
$path = explode(‘/’, $_SERVER[“DOCUMENT_ROOT”]);
// printing the first element of the root directory path array
echo $path[0];  // output: C:
?>

PHP Root Directory Path: Comparing the Magical Constants

Interestingly, the __DIR__ and __FILE__ constants provide almost similar results. The only exception between both of them is that the __DIR__ constant returns the path of your current directory. On the other hand, the __FILE__ constant gives back the path of your current file. Therefore, you will notice a difference of one level when you use them inside the dirname() function.

– Coding Example for Comparing the Magical Constants

Let’s assume that you are willing to find the results returned by the two magical constants and their effect with the dirname function

If you have found yourself in such a case, then you should follow these coding instructions to save your time:


echo __DIR__ . “
”;

// output: C:xampphtdocsMyFolder
echo dirname(__DIR__) . “
” ;

// output: C:xampphtdocs
echo __FILE__ . “
”;

// output: C:xampphtdocsMyFoldermyFile.php
echo dirname(__FILE__);
// output: C:xampphtdocsMyFolder
?>

Winding Up

Undoubtedly, being familiar with your PHP root directory path can be quite helpful while working on large projects. Having covered different ways to get the base directory path, here are some notable facts to help you ensure the correctness of your concepts:

  • The $_SERVER[“DOCUMENT_ROOT”] returns the PHP root directory of your current file
  • In PHP versions before 5.3, you can use the dirname() function with the __FILE__ constant and a level >= two to PHP get base directory of your current file
  • In PHP version from 5.3 and over, you can use the dirname() function with the __DIR__ constant to PHP get base directory of your current directory
  • You can get to the root directory by using the chroot() function in BSD and GNU Operating Systems
  • The combo of the explode() function with $_SERVER[“DOCUMENT_ROOT”] serves to be an efficient way to get the root directory

How do i get to the root directory in php?
The blocks of code given above will provide you with the results that’ll align with your current directory structure. You can also try placing your script in different folders to see how the returned paths change with every switch.

  • Author
  • Recent Posts

How do i get to the root directory in php?

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

How do i get to the root directory in php?

How do I go back to the root directory in PHP?

The chroot() function changes the root directory of the current process to directory, and changes the current working directory to "/".

How do I get to the root directory?

To locate the system root directory: Press and hold the Windows key, then press the letter 'R'. (On Windows 7, you can also click start->run… to get the same dialog box.) Enter the word “cmd” in the program prompt, as shown, and press OK.

Where is my root directory path?

For the Grid, a website's root directory is the …/html folder. This is located in the file path /domains/example.com/html. The root directory can be viewed/accessed through File Manager, FTP, or SSH.

How do you go up a directory in PHP?

If you are using PHP 7.0 and above then the best way to navigate from your current directory or file path is to use dirname(). This function will return the parent directory of whatever path we pass to it.