When the same PHP application runs through a web server and the command line, $_SERVER['SCRIPT_FILENAME'], $_SERVER['SCRIPT_NAME'] and $_SERVER['DOCUMENT_ROOT'] may contain different values. The most reliable solution is to stop using these server variables to calculate your application's filesystem root. Instead, establish a consistent application root using DIR and dirname(), or supply an explicit configuration value when your deployment requires it.
This approach works with native PHP applications, scheduled scripts, background workers and applications deployed behind Apache, Nginx or PHP-FPM.
Why SCRIPT_FILENAME behaves differently in PHP CLI
PHP populates the $_SERVER superglobal with information about the current execution environment.
When PHP runs through a web server, values such as SCRIPT_NAME and SCRIPT_FILENAME generally describe the requested PHP entry point.
For example, a website might have the following values:
text
SCRIPT_NAME = /index.php
SCRIPT_FILENAME = /var/www/example/public/index.php
DOCUMENT_ROOT = /var/www/example/public
When the same application runs through PHP CLI, these values may differ because there is no HTTP request or web-server document root.
For example:
php /var/www/example/scripts/import.phpThe script being executed is now import.php rather than index.php.
The CLI environment also does not inherently have a web document root. DOCUMENT_ROOT may be missing or empty.
See the PHP predefined $_SERVER variables documentation for details about these values.
Why overriding SCRIPT_FILENAME with environment variables fails
A developer might attempt to replace PHP's script information using shell environment variables:
SCRIPT_NAME=/index.php SCRIPT_FILENAME=/var/www/example/public/index.php php scripts/import.phpHowever, SCRIPT_NAME and SCRIPT_FILENAME are special values that PHP may populate independently of the environment variables supplied by the shell.
Consequently, assigning those names before starting PHP does not reliably override their corresponding $_SERVER entries.
Ordinary custom environment variables behave differently.
For example:
APP_MODE=import php scripts/import.phpPHP can retrieve the custom value using:
<?php
$mode = getenv('APP_MODE');
echo $mode;The distinction is important: getenv() reads an environment variable, while $_SERVER can contain values generated by PHP or supplied by the web-server interface.
It is technically possible to modify $_SERVER inside a running PHP script, but changing interpreter-provided values to disguise the current execution environment is not a reliable application configuration strategy.
Use your own configuration variables instead.
Why calculating the document root with str_replace is fragile
Consider this approach:
<?php
$root = str_replace(
$_SERVER['SCRIPT_NAME'],
'',
$_SERVER['SCRIPT_FILENAME']
);This attempts to calculate a filesystem root by removing the script's URL path from its physical filename.
It can appear to work when the web-server configuration follows a particular directory structure.
However, it makes several assumptions.
First, SCRIPT_NAME and SCRIPT_FILENAME must refer to compatible paths.
Second, the URL path must correspond directly to the filesystem layout.
Third, the expected script information must exist in the current execution environment.
These assumptions can fail when applications use front controllers, URL rewriting, reverse proxies, symbolic links or command-line entry points.
A scheduled script may also execute from a different directory than the website's index.php.
An application should not have to reconstruct its filesystem structure from HTTP request information.
Understanding application root versus document root
Before fixing the paths, distinguish between two directories.
The application root is the main directory containing the application's configuration, source files, scripts and dependencies.
The document root is the directory exposed by the web server for HTTP requests.
A typical PHP application might have this structure:
text
my-app/
bootstrap.php
config/
app.php
public/
index.php
scripts/
check.php
In this example, my-app is the application root.
The public directory is the web document root.
The config and scripts directories should not be directly accessible through HTTP.
Keeping these paths separate allows the same application code to run through a browser or the command line without depending on the current request.
Complete working example: Shared PHP bootstrap
The following example demonstrates a small PHP application that uses the same configuration in both environments.
Create the directory structure shown above and add the following four files.
1. bootstrap.php
Place bootstrap.php directly inside the application root.
<?php
declare(strict_types=1);
$appRoot = __DIR__;
$publicRoot = $appRoot . '/public';
$configFile = $appRoot . '/config/app.php';
if (!is_dir($publicRoot)) {
throw new RuntimeException(
'Public directory does not exist.'
);
}
if (!is_file($configFile)) {
throw new RuntimeException(
'Application configuration is missing.'
);
}
return [
'app_root' => $appRoot,
'public_root' => $publicRoot,
'config' => require $configFile,
];The important line is:
php
$appRoot = __DIR__;
The DIR magic constant returns the directory containing the current PHP file.
Because bootstrap.php lives in the application root, it provides a consistent reference point regardless of which script loads it.
It does not depend on the current working directory, SCRIPT_FILENAME, SCRIPT_NAME or DOCUMENT_ROOT.
The bootstrap file returns an array containing the paths and application configuration.
2. config/app.php
Create the application configuration file:
<?php
declare(strict_types=1);
return [
'name' => 'Example PHP Application',
'environment' => 'development',
];In a production application, environment-specific values should come from trusted deployment configuration rather than being hardcoded into publicly accessible source files.
Never store production database passwords or API keys in a publicly accessible directory.
3. public/index.php
This is the HTTP entry point.
<?php
declare(strict_types=1);
$app = require dirname(__DIR__) . '/bootstrap.php';
header('Content-Type: text/plain; charset=UTF-8');
echo $app['config']['name'] . PHP_EOL;
echo 'Web bootstrap loaded successfully.' . PHP_EOL;The expression dirname(DIR) moves one directory above public, where bootstrap.php is located.
There is no need to inspect the web server's SCRIPT_FILENAME or DOCUMENT_ROOT values.
The application loads its configuration using a path derived from the physical location of the PHP file.
4. scripts/check.php
Create a command-line script that loads the same bootstrap file.
<?php
declare(strict_types=1);
if (PHP_SAPI !== 'cli') {
http_response_code(403);
exit('This script must run through PHP CLI.');
}
$app = require dirname(__DIR__) . '/bootstrap.php';
echo 'Application: ' . $app['config']['name'] . PHP_EOL;
echo 'Environment: ' . $app['config']['environment'] . PHP_EOL;
echo 'PHP interface: ' . PHP_SAPI . PHP_EOL;
echo 'Application root: ' . $app['app_root'] . PHP_EOL;
echo 'Public root: ' . $app['public_root'] . PHP_EOL;This script uses exactly the same bootstrap file as the HTTP entry point.
The difference is that it explicitly checks whether PHP is running through CLI before executing.
The application root and public root remain consistent because both entry points resolve bootstrap.php relative to their own locations.
Running the example
From the application root, execute the command-line script:
php scripts/check.phpExample output:
text
Application: Example PHP Application
Environment: development
PHP interface: cli
Application root: /var/www/my-app
Public root: /var/www/my-app/public
The actual paths depend on where you created the application.
To test the web entry point locally, start PHP's built-in development server:
php -S 127.0.0.1:8000 -t publicOpen the local address in your browser.
You should see the application name followed by a confirmation that the web bootstrap loaded.
PHP's built-in server is intended for development and testing, not public production hosting.
Why DIR is safer than getcwd()
Another common mistake is using getcwd() to determine the application root.
For example:
<?php
$root = getcwd();The getcwd() function returns the process's current working directory.
That directory can change depending on where a command is launched, how a cron job is configured or whether another part of the application calls chdir().
For example, executing a PHP script from a different directory does not guarantee that getcwd() will return the application's directory.
By comparison, DIR is associated with the PHP file containing it.
Use getcwd() when you specifically need the current working directory. Use DIR or an explicitly configured path when you need a stable reference to application files.
The PHP magic constants documentation explains how DIR and FILE behave.
Detecting CLI versus web execution
Sometimes application behaviour must differ depending on how PHP is running.
PHP provides the PHP_SAPI constant for this purpose.
<?php
if (PHP_SAPI === 'cli') {
echo 'Running from the command line';
} else {
echo 'Running through another PHP interface';
}This distinguishes the ordinary PHP CLI interface from other interfaces. The else branch is not guaranteed to mean an HTTP request because PHP supports additional execution interfaces.
For most scheduled scripts, checking for cli is appropriate.
However, avoid scattering environment checks throughout the application merely to locate files.
The bootstrap approach generally eliminates the need for different path calculations.
Use execution-environment checks only where behaviour genuinely needs to differ, such as preventing a maintenance script from running through HTTP.
Using environment variables for deployment-specific paths
Some applications need an application root that cannot be determined from a fixed directory relationship.
Examples include shared code deployments, external storage locations or applications using configurable filesystem mounts.
In those cases, use a dedicated environment variable rather than trying to override SCRIPT_FILENAME.
For example:
APP_ROOT=/var/www/my-app php scripts/check.phpA bootstrap file can support an optional configured root:
<?php
declare(strict_types=1);
$configuredRoot = getenv('APP_ROOT');
if (is_string($configuredRoot) && $configuredRoot !== '') {
$appRoot = realpath($configuredRoot);
} else {
$appRoot = __DIR__;
}
if ($appRoot === false || !is_dir($appRoot . '/public')) {
throw new RuntimeException('Invalid application root.');
}This is an alternative root-resolution strategy, not an additional file required by the earlier working example.
The configured directory should come from trusted server or deployment configuration, not directly from an HTTP request parameter.
The realpath() function resolves an existing filesystem path to its canonical form. It returns false when the path cannot be resolved.
Why this matters for cron jobs
Scheduled PHP scripts frequently expose path problems that remain hidden during ordinary browser requests.
For example, a developer might configure a cron job using:
php scripts/import.phpThis relies on the scheduled process starting in the correct working directory.
A more reliable command uses absolute paths:
/usr/bin/php /var/www/my-app/scripts/import.phpThe PHP interpreter path must match the installation available on your server.
Inside import.php, load the shared bootstrap using a path relative to the script itself:
<?php
declare(strict_types=1);
$app = require dirname(__DIR__) . '/bootstrap.php';Now the application can locate its files regardless of the directory from which cron launches the command.
This is particularly useful for scheduled imports, report generation, email processing, API synchronisation and database maintenance tasks.
If the application runs through cPanel, WHM or shared hosting, confirm that the scheduled command uses the correct PHP CLI version and that the account has permission to access the relevant directories.
Common PHP path mistakes
Several mistakes cause applications to behave differently between HTTP and CLI execution.
Using DOCUMENT_ROOT as the application root assumes that the public directory and application directory are the same. Modern applications often keep private code outside the document root.
Using SCRIPT_FILENAME as the root assumes that the currently executing script is located in a predictable directory. That assumption fails when separate CLI entry points exist.
Using relative require paths without DIR can create dependencies on the current working directory or PHP's include_path configuration.
Using getcwd() to locate configuration files can fail when scheduled jobs start from an unexpected location.
Finally, using filesystem paths to construct public URLs confuses two separate concepts. A URL path does not necessarily correspond directly to a physical directory structure. Configure a public base URL separately when the application needs to generate absolute HTTP links.
Testing across different environments
Before deploying an application that supports both web and command-line execution, verify the following behaviour.
Run the CLI script from the application directory, then run the same script using an absolute path from another directory. Both executions should resolve the same application root.
Run the web entry point through your normal web server and confirm that the application loads without relying on DOCUMENT_ROOT.
Check that configuration files outside the public directory cannot be requested directly through HTTP.
Test scheduled tasks with the PHP CLI binary available on the production server. Confirm that the expected PHP extensions and environment variables are available.
If your deployment uses symbolic links or release directories, verify which physical directory DIR resolves to and ensure that your configuration matches the intended release.
Final recommendations
Do not override PHP's built-in SCRIPT_NAME or SCRIPT_FILENAME values to make CLI execution resemble an HTTP request.
Instead, establish your application root from a known bootstrap file and use that root consistently throughout the application.
Keep the application root separate from the public document root, use absolute paths for scheduled commands and reserve environment variables for genuine deployment configuration.
This approach avoids fragile path calculations and makes PHP applications easier to deploy across Apache, Nginx, PHP-FPM, shared hosting and command-line environments.
For additional reference, consult the PHP dirname() documentation, PHP predefined server variables and PHP SAPI documentation.
