2

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

user3840170
  • 26,597
  • 4
  • 30
  • 62
  • *via SSH*: you meant by running your script like `php cronMin.php` on the command line ? – AymDev Dec 31 '21 at 09:11
  • There is no `$_SERVER['DOCUMENT_ROOT']` set when accessing PHP via CLI – brombeer Dec 31 '21 at 09:12
  • Yes, like this: `/usr/local/cwp/php71/bin/php -d max_execution_time=18000 -q /home/example/public_html/app/cron/cronMin.php` –  Dec 31 '21 at 09:13
  • When PHP is running in your webserver, it is likely `chroot`-ed, judging by the path `/app/config.php`. When you're in a terminal you likely are not, so the correct path might be `/var/www/html/app/config.php` for example. edit: or you were using a web specific prefix like @brombeer suggests; same end result. – Raxi Dec 31 '21 at 09:13
  • A cron script shouldn't be under `public_html`. Command-line tools have nothing to do with HTTP and you don't want random visitors (e.g. Google indexer) to execute your maintenance talks at will. – Álvaro González Dec 31 '21 at 10:44

1 Answers1

4

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';
AymDev
  • 6,626
  • 4
  • 29
  • 52
  • Be aware that __DIR__ is the current directory your script runs in. So if you have nested folder structure __DIR__ will not be equivalent to $_SERVER['DOCUMENT_ROOT'] as it would be some subdirectory of root – leuchtdiode Dec 31 '21 at 10:49