How to Find the Document Root using PHP Script

Техника
Find Root Directory Path in PHP

We will introduce different methods to find the path of the root directory of a PHP project.

Shraddha Paghdar
Nov 03, 2021

Document Root in PHP

Your PHP script may need the root directory name in which the script is currently executing. This article will introduce how to get the directory name of the current script inside the project.

Php get root directoryThe 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.

  • Get Root Directory: Use the Super Global Variable
  • Get Base Directory: Execute the Dirname() Function
  • PHP Root Path: Use Dirname() With __DIR__
  • How To Get To Root Directory in PHP: Use Chroot()
  • PHP Get Root Directory of Website: Going to the Top
  • PHP Root Directory Path: Comparing the Magical Constants
  • 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

Get the absolute path

If your script is included in /path/directory/, this code snippet:

$base_dir = __DIR__;

..returns something like this (depending on actual server path):

Note that the result does not include a trailing slash.

Get the document root

The easiest, cleanest way to get the document root:

$doc_root = $_SERVER['DOCUMENT_ROOT'];

..which returns something like:

Note that the result does not include a trailing slash.

Alternately you can do this:

$doc_root = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", '', $_SERVER['SCRIPT_FILENAME']);

The first way is preferred, the second way is for your information.

Get base URL of current script

// base directory
$base_dir = __DIR__;

// server protocol
$protocol = empty($_SERVER['HTTPS']) ? 'http' : 'https';

// domain name
$domain = $_SERVER['SERVER_NAME'];

// base url
$base_url = preg_replace("!^${doc_root}!", '', $base_dir);

// server port
$port = $_SERVER['SERVER_PORT'];
$disp_port = ($protocol == 'http' && $port == 80 || $protocol == 'https' && $port == 443) ? '' : ":$port";

// put em all together to get the complete base URL
$url = "${protocol}://${domain}${disp_port}${base_url}";

echo $url;

That will output something like this:

Дополнительно:  Плохие отзывы о AVerMedia Technologies DVD EZMaker 7

Note that the result does not include a trailing slash.

WP-Mix File-Path Trilogy

The document root, also known as the web root, is the topmost directory in your web server’s file structure where your website’s files and folders are stored. It is a crucial aspect of web development, as it serves as the starting point for your website. In this article, we will explore how to find the document root using PHP scripts, which will help you manage your website more effectively and enhance your web development skills.

Step 1: Understanding the $_SERVER Variable

Step 2: Displaying the Document Root

  1. Open your preferred text editor or integrated development environment (IDE).
  2. Create a new PHP file and save it with a .php extension, such as “find_document_root.php”.
  3. Add the following code to your newly created PHP file:
  4. Save the changes to the file.
  5. Upload the “find_document_root.php” file to your web server.
  6. Access the script via your web browser using your domain or server’s IP address, followed by the script’s file path (e.g., http://example.com/find_document_root.php).
Identifying Your Document Root using PHP Script
Getting the Document Root using PHP

The output may differ depending on your server’s configuration and operating system. The displayed path is the location where your website’s files and folders are stored on the server.

Step 3: Using the Document Root in Your PHP Scripts

Once you know your document root, you can use it in your PHP scripts to access files or directories relative to the document root. This helps ensure that your file paths are consistent and accurate, regardless of where your script is located within your website’s file structure.

  1. In your PHP script, assign the value of $_SERVER[‘DOCUMENT_ROOT’] to a variable:
  2. When referencing files or directories in your script, concatenate the $docRoot variable with the relative path:

By using the document root variable in your PHP scripts, you can ensure that your file paths are accurate and reliable, regardless of the script’s location within your website’s structure.

Conclusion

Часто возникает необходимость подгрузить из одного скрипта другой. Всё хорошо, когда эти скрипты физически расположены в одном каталоге. Делаем include и нет проблем. Проблемы возникают при развитой системе скриптов. Когда исполняемые файлы сгруппированы по каталогам и нужно настроить взаимодействие между ними.

Для себя я решил, что проще всего понять где находится корневой каталог и уже от него подгружать другие скрипты.

Способ 1. Некрасивый

     
PATH

Плюсы данного решения

– Должен работать даже на самых древних версиях PHP.

– Инициализация константы происходит в одну строку.

Минусы данного решения

– В зависимости от вложенности скрипта, необходимо менять количество "../". То есть, если вложенность один каталог:

PATH

Если вложенность 4 каталога:

PATH

– Весь этот код вообще не нужен ведь, начиная с PHP 5.3, появилась константа __DIR__, которая содержит путь к каталогу.

php varwwwsiteslgnd.rupublic_htmlparsertest.php

Но если вы сначала перейдете в каталог скрипта, а затем запустите его:

 varwwwsiteslgnd.rupublic_htmlparsertest.php
php test.php

Способ 2. Элегантный, но не идеальный

В какой-то момент мне надоело постоянно менять вложенность. И я решил переписать этот говнокод.
Начиная с PHP 5.3, появилась удобная константа __DIR__. Почему бы не воспользоваться ею?

Для начала определим: какое название имеет корневой каталог. В зависимости от настроек вашего веб-сервера, это может быть public_html, public, www или что-то другое. В константе __DIR__ будет такой путь:
/var/www/sites/lgnd.ru/public_html/parser

К этой строке мы добавляем название корневого каталога и слэш.

  
   __DIR__
  
PATH

Плюсы

– Будет корректно определён путь до корневого каталога, вне зависимости от вложенности скрипта.

– Нет проблем с относительным/абсолютным путем при работе из командной строки или при запуске в экзотических конфигурациях

– Не нужно постоянно указывать дополнительные "../" при переносе скрипта в другой каталог.

Минусы

– Требует PHP 5.3+

– Инициализация занимает больше строк и её нельзя сократить (записать три строки в одну не комильфо)

– Требует указания корневого каталога, а значит скрипт нельзя просто скопировать с одного сервера на другой

Способ 3. Нет предела совершенству

Дальнейшие улучшения способа номер 2.

В PHP 5.4 появилось разыменование массивов. Эта штука позволяет обращаться к результатам работы функции explode без создания временной переменной:

   __DIR__
 
  __DIR__

В итоге код из способа 2 становится более компактным:

  
   __DIR__

А если очень хочется всё записать в одну строку:

   __DIR__

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 . 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.

Дополнительно:  Терминал под root что это

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:

PHP Get Root Directory of Website

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 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

$_SERVER in PHP

$_SERVER is an array that contains information about headers, paths, and script locations. The webserver creates all this information. You can use an array to get details of a specific location, like PHP_SELF, SCRIPT_NAME, DOCUMENT_ROOT, etc.

DOCUMENT_ROOT in PHP

It’s not advisable to set the static path for any file because the change of root path will lead to a failure if the path inside the script is not changed. $_SERVER contains information about the document root directory under which the current script is executing. It is accessible via the variable DOCUMENT_ROOT, as defined in the server’s configuration file. This is the path where your application code is stored.

Shraddha Paghdar avatar
Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

Use $_SERVER[‘DOCUMENT_ROOT’] to Find the Document Root Directory of a File in PHP

As shown in the output below, we found out the path html is the document root directory of the login.php file. We can see the file path of the root directory as well.

How To Get To Root Directory in PHP

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

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

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

Дополнительно:  Неисправность северного моста материнской платы признаки - Всё о компьютерах

Use the Super Global Variable

You might find it hard to believe but the super global variable can help you in finding the PHP root directory path. Certainly, the PHP root path is stored on the 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

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

Use the dirname() Function to Find the Path of the Root Directory of a Project in PHP

The function dirname(__FILE__) is similar to __DIR__. We can find the path of the directory of a file using this function. We can also move to the upper levels in the file path using the dirname() function. The first parameter of the function is the path of the file, which is denoted by the __FILE__ constant. The second parameter is an integer which is called levels. We can set the levels to direct the function to level up in the file path. The default value of the level is 1. As we increase the level, the function will get the file path of one level up. So, we can use this function to find the exact file path of the project’s root directory in PHP.

For example, we can consider the file structure as the first method. Working from the file, login.php, we can use the dirname() function with level 2 and the __FILE__ constant as parameters. Then we can get the exact file path of the working directory. Thus, we can change the levels according to our choice to move upward and downward in the file path. In this way, we can find the path of the root directory of the project in PHP.

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 . 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:

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

Use the __DIR__ Predefined Constant to Find the Path of the Directory of a File in PHP

In PHP, there are predefined constants that can be used to achieve various functionalities. __DIR__ is one magical constant that returns the complete file path of the current file from the root directory. It means it will return the file’s directory. dirname(__FILE__) can also be used for the same purpose.

Оцените статью
Master Hi-technology
Добавить комментарий