Finding Exact Document Root in PHP

PHP

Read {count} times since 2020

You might know the DOCUMENT_ROOT value of the $_SERVER array. This value indicates the absolute location of the site directory where pages are served. In short, it’s the public folder of site as defined in the server’s configuration. Here’s a quick example :

If you have a site in /home/me/site and can access it by http://site.dev, then the $_SERVER[‘DOCUMENT_ROOT’] is “/home/me/site”.

If any page in the server, even if it is in many sub folders, the DOCUMENT_ROOT value will be the same.

This is totally depended on the site’s configuration. This value won’t be the same in your localhost server and on the server in the web.

In an other case, if you have a project or library that requires accessing files inside it which will be used in many server environments, accessing files by $_SERVER[‘DOCUMENT_ROOT’] is not efficient and possible. In this case, we have to find another way to precisely calculate the library’s document path.

Any library will have a file that’s loaded first. As an example, we assume it as “load.php” in the “library” directory and this is the file which includes it :

<?php
include "library/load.php";
?>

and in load.php, we include an other file which is in the library’s directory called “file2.php”. Here is how we do it with $_SERVER[‘DOCUMENT_ROOT’] :

<?php
include $_SERVER["DOCUMENT_ROOT"] . "/library/file2.php";
?>

But, we cannot be sure that the directory containing the library is named “library”. So, we should calculate it in the correct way :

<?php
include realpath( dirname(__FILE__) ) . "/file2.php";
?>

The above will work in all server environments which run PHP 5. The above code can be shortened in another way :

<?php
include realpath(__DIR__) . "/file2.php";
?>

Both the ways is the same. Note that we are obtaining the absolute path of the “library” directory from the “load.php” file. So, we don’t need to add “library” before “/file2.php”.

Be sure to use this when you are creating a library in PHP for more efficiency and perfect performance in various environments,

Show Comments