Identify development vs. production server in PHP

Viewed 10417

I work with two application servers on a daily basis: one development, one production. A variety of apps from different developers live on these boxes, as well as some scripts that run via cron. Currently, I am using the -D flag to httpd so that I can identify my production server in code, ie. isset($_SERVER['DEV']). Unfortunately, this does not work for scripts run from the command line since they're not under the Apache umbrella.

Essentially, I would like a clean, simple way to identify development vs. production that is available to every line of code.

What I have ruled out:

  • auto_prepend_file -- we are already using this directive in some applications, and you can't have more than one autoprepend.

What I am currently exploring:

  • Custom extension -- I'm sure creating a new extension that only defines a new constant (possibly influenced by an ini setting) would not be the hardest thing in the world, but I have no prior experience in this area.

So, got any tricks for identifying dev/prod that doesn't involve injecting code into every script or application?

5 Answers

I ended up using $_ENV['HOSTNAME'], with php_uname("n") as a backup:

/**  
 * Returns true if we are working on a development server, determined by server's
 * hostname. Will generate an error if run on an unknown host.
 */
public static function isdev()
{
  static $isdev = null;

  // don't run function body more than once
  if( null !== $isdev ) {
    return $isdev;
  }    

  // prefer HOSTNAME in the environment, which will be set in Apache.
  // use `uname -n' as a backup.
  if( isset( $_ENV['HOSTNAME'] ) ) {
    $hostname = $_ENV['HOSTNAME'];
  } else {
    $hostname = php_uname("n");
  }    

  switch( $hostname ) {
    case 'production1.example.com':
    case 'production2.example.com':
    case 'production3.example.com': $isdev = false; break;

    case 'dev1.example.com':
    case 'dev2':
    case 'dev2.example.com': $isdev = true; break;

    default: trigger_error( 'HOSTNAME is set to an unknown value', E_USER_ERROR );
  }    

  return $isdev;
}

A company I worked for previously used a convention of suffixing servers as follows:

  • L = Live
  • D = Dev
  • T = Test
  • U = UAT

This makes determining the environment that you're working on, both inside and outside of Apache, fairly trivial.

Related