Detecting which server a cron job is running from

I have a script that needs to be run on a couple different servers every night. Problem is that each server has different database credentials, so I need to set the correct user name and password for each, otherwise it won’t work.

I thought about having a config file for each, but I wanted all code to be pulled from my git repository and not rely on other files that are supposed to be there.

First I thought it would be no problem – just check the $_SERVER[’SERVER_NAME’] and set credentials accordingly. This works fine when running through the shell, but when triggered through cron it kept failing. The problem is that when cron scripts are run most of the $_ENV variables aren’t set.

My workaround was just to use the __FILE__ ‘magic constant’, which is set even with cron. Luckily the different servers have different paths where the script is running from, so Example code:

if(strstr(__FILE__,"/serverpath1/"))
{
	$user = "xxx"; $pass = "xxx";
}
elseif(strstr(__FILE__,"/serverpath2/”))
{
	$user = "yyy"; $pass = "yyy";
}

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *