Question

I have some PHP scripts for database maintenance in my server that requires its periodically execution. Obviously the easiest solution is to schedule its running with system cron.

The scripts require some server variables accessed from $_SERVER, like database hostname, cron parameters, etc.

I can run the scheduled cron commands from command line without any problem, and everything seems to be working fine (calling something like php filename.php). However, when the same commands are executed from cron, the scripts fails and the error reported is like the following:

PHP Notice: Undefined index: RDS_DATABASE in /var/app/current/app/xx/Db/ConnectionFactory.php on line 8 PHP

Seems that the $_SERVER variable is not correctly initialized when running from cron, but it works from command line. I have tried with crontab -u ec2-user -e but without luck.

I do not want to use wget to run the script as it adds some overhead, and the scripts are hidden from being accessed from HTTP.

Any hint about successfully accessing $_SERVER from command line, but failing when running from crontab?

Was it helpful?

Solution

Had the same issue. Found a solution:

echo "InstanceID: ".get_cfg_var('INSTANCE_ID')."\n";

For some reason it was working fine on my ec2 user but not as a root cron job. Using the function instead of accessing the $_SERVER array solved my problem.

OTHER TIPS

$_SERVER only works if you will run PHP using any web server. If you will use crontab and execute PHP via command line it will not work. You may refer to PHP documentation http://php.net/manual/en/reserved.variables.server.php#refsect1-reserved.variables.server-indices

As @Baminc and @Ankur says the solution is to use get_cfg_var function to get the information because $_SERVER only works when you access it from a web browser.

What I do is the following for example with SERVER_NAME :

if (isset($_SERVER['SERVER_NAME'])) {
    $myServerName = $_SERVER['SERVER_NAME'];
} else {
    $myServerName = get_cfg_var('SERVER_NAME');
}

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top