How to Get the Absolute Path to the Initially Run Script in PHP

Modern developers are often in search of reasonable solutions to the issue of getting the absolute path to the initially run script.

We have chosen the most accurate and valuable solution to the problem. Just check out the example below.

Using the get_included_files Function

The most accurate method of getting the absolute path to the initially run script in PHP is using the get_included_files function.

Here is an example of its usage:

get_included_files function:

list($scriptPath) = get_included_files();

After using this function, you will get the absolute path of the script even in the following cases:

  • the function is located in an included file;
  • the initial script directory is different from the current working directory;
  • as a relative path, the CLI is applied for running the script.

Now let’s see two scripts. One of them is the included file, and another one is the main script:

# C:\Users\Redacted\Desktop\main.php include __DIR__ . DIRECTORY_SEPARATOR . 'include.php'; echoScriptPath(); # C:\Users\Redacted\Desktop\include.php function echoScriptPath() { list($scriptPath) = get_included_files(); echo 'The script being run is ' . $scriptPath; }

The result will look as follows:

C:\>php C:\Users\Redacted\Desktop\main.php The script being run is C:\Users\Redacted\Desktop\main.php

Describing the get_included_files Function

This function is supported by PHP 4, PHP 5 and PHP 7 versions.

It is capable of returning an array with the namings of the required or included files.

The initially called script is known as the included file. Hence, it is listed with the files that are referenced by the include and family.

All the files that are required or included several times will appear only once within the returned array.