Home > front end >  $_SERVER['DOCUMENT_ROOT'] does not work in command-line PHP. How do I fix this?
$_SERVER['DOCUMENT_ROOT'] does not work in command-line PHP. How do I fix this?

Time:12-31

I am able to access the PHP page in the web browser without error and works. (error display active)

But when I want to access the PHP page via SSH I get some errors.

PHP Warning: include_once(/app/config.php): failed to open stream: No such file or directory in /home/example/public_html/app/cron/cronMin.php on line 7

SSH Command:

/usr/local/cwp/php71/bin/php -d max_execution_time=18000 -q /home/example/public_html/app/cron/cronMin.php

cronMin.php:

<?php
    
    use Carbon\Carbon;
    
    ini_set('memory_limit', '3G');
    ini_set('max_execution_time', 180);
    include $_SERVER['DOCUMENT_ROOT'] . '/app/config.php';
    ...

What is the reason for this?

PHP 7.4 - Apache, Nginx, and Varnish

CodePudding user response:

From the $_SERVER documentation:

The entries in this array are created by the web server.

When running PHP on the command line, there is no web server involved, that means no $_SERVER['DOCUMENT_ROOT'].

If your scripts must run the same with the CLI SAPI and a web server SAPI, don't rely on such variables. To include other PHP scripts, use the __DIR__ magic constant instead:

// cronMin.php is in the "app/cron" directory, this will be the value of __DIR__ as an absolute path
include __DIR__ . '/../config.php';
  • Related