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

Tags: , , ,
Related posts
Bookmark: Post to Del.icio.us Post to Digg Post to Google Post to Ma.gnolia Post to MyWeb Post to Newsvine Post to Reddit Post to Simpy Post to Slashdot Post to Technorati

2 Responses to “PHP crons, linux, and the hostname”

  1. super Says:

    http://us.php.net/php_uname

    php_uname(‘n’);

  2. John Says:

    Thanks for that tip! It is a much better way of doing it. I’ve updated a few of our crons to reflect this.

Leave a Reply