I use $_SERVER[\'DOCUMENT_ROOT\'].\"/lib/sft_required.php\"; to include the \'sft_required\' file in a PHP script. When I run this file using browser, it works fine but whe
In my case, this issue was caused by the $_SERVER['DOCUMENT_ROOT']
path having a trailing slash during normal site operations and no trailing slash during cron jobs.
I'm not sure what was causing that to happen, but as a workaround, I switched my code to use ABSPATH
instead, since it appeared to be returning a consistent value.
So, in other words, I changed this:
$private_folder = realpath($_SERVER['DOCUMENT_ROOT'] . "../private_html");
to this:
$private_folder = realpath(ABSPATH . "../private_html");
There are several other solutions to that problem as well, such as using str_replace
or rtrim
.
Assuming you are running the script directly through cron (as opposed to from a web server accessed by an HTTP request triggered by a cronjob (e.g. by cron running wget)), then of course it doesn't work.
There is no server, so $_SERVER
is not set.
you could populate the $_SERVER['DOCUMENT_ROOT'] on your own
$_SERVER['DOCUMENT_ROOT'] = dirname(__FILE__);
if the cron file is in document root
$_SERVER['DOCUMENT_ROOT'] = dirname(dirname(__FILE__));
if the cron file is one directory above the document root
I had same problem.. And solutions what i found on internet not worked with my webserver cron, so i needed find another way to change that path easly..
And its mostly not big problem, when yu have 1-2 cron files(can easly edit file path if needed), but i had 20 cron files and when i need change server or path changed or smt, then i must change all those files, change file path on them...
So i found atleast FOR ME exellent solutions: i maded one file path.php in cron folder and bc its same folder with cron files, then you can include it without errors.
And in path.php i have $path = '/server/root/path';
And then i include that path.php to my cron files(i have 20 cron files or so)
And now i use that $path on my cron files as below:
include 'path.php';
include $path.'/includes/db.php';
Now if i need change path, then i just open path.php file , change it and all working.
Hope i helped someone, bc that solutions changed my life much much easyer! Its still not perfect, bc perfect would be when all worked automatically, but for me that is much much easyer than previous system, so i tought i will share my experience, mabe i can help someone :)!
I answered a similar question here. As people have mentioned, the superglobal $_SERVER isn't defined in CLI situations. In the link is a (so far) foolproof method for obtaining the DOCUMENT_ROOT location. Hope it proves useful.
$_SERVER
cannot be expected to contain any of the normal values when a PHP script is run using the CLI interpreter. Either put the path in an environment variable, or pass it to the script as a command line argument.