PHP crons, linux, and the hostname
When running PHP as a cron, the $_SERVER['HOSTNAME'] variable is not set, nor are any other variables that will identify which server your cron is running on. This can be problematic if you are running the same cron on multiple servers, such as in a load balanced environment, and you need the cron to report back or log information about the server on which it ran.
Here is some code for getting the hostname value from your linux network configuration, assuming you have setup /etc/sysconfig/network properly.
//get hostname info from /etc/sysconfig/network
preg_match('/HOSTNAME=(.*)/', file_get_contents('/etc/sysconfig/network'), $network);
$hostname = split("\=", $network[0]);
echo $hostname[1]; //this equals the value of your HOSTNAME











June 22nd, 2009 at 1:20 pm
http://us.php.net/php_uname
php_uname(‘n’);
June 22nd, 2009 at 1:44 pm
Thanks for that tip! It is a much better way of doing it. I’ve updated a few of our crons to reflect this.