开发者

Detecting if a Cron job is running on a staging server

I'm building a website that will run a series of cron tasks daily to update information in a database that is then used in the site. I have three environments setup: development (my computer), staging and live. Both staging and live are accounts on shared hosting. The problem I have is in deciding which database access credentials to use depending on which environment the code is running on. Ideally all three would have the same credentials but as both staging and live are on a shared server I c开发者_JAVA技巧an't control the name of the database. I've mirrored the live database name and access credentials on my own computer but I can't do this on staging.

What I want to do is to automatically select the correct credentials for the correct environment when my cron task runs, something like this:

if(environment === staging) {
  //define db access constants for staging here
 else {
  //define db access constants for live or dev here
}}

Normally for this sort of thing I'd use $_SERVER['SERVER_NAME'] but as this is running in Cron the $_SERVER auto global isn't available. How could I detect on which environment a script is running in a cron job?


You could put an extra environment variable in the crontab file:

STAGING=1

and then check for $_ENV['STAGING'] == 1.

Or even

HOSTING_ENV=PRODUCTION

and then check for $_ENV['HOSTING_ENV'] == 'PRODUCTION'.


The environment variable solutions that ajreal and gms8994 are both good. Another method is to use php_uname() to fetch the current hostname:

sean@gimmebarvm-sean:~$ php -r 'echo php_uname("n") . "\n";'
gimmebarvm-sean


run your cron via WGET by calling it by a domain rather by PHP command line

you will then be able to detect the platform by its domain

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜