Alvaro Luis Bustamante Alvaro Luis Bustamante - 1 year ago 527
PHP Question

Crontab on AWS EC2 and $_SERVER PHP variables

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download