Determining the environment in your application

Wednesday, March 25, 2009

Every user has another way to do it, and for every project it has to be a bit different than before. I'm talking about the decision in which environment your application currently runs. In the past, I always let it depends on the hostname, but that got tricky and dirty, when it was available via multiple hostnames, if a hostname changes or when another developer wanted to checkout the source and work on it.

After some looking around, i found mod_env of apache, which lets you set environment variables accessible by PHP. It works like that, first you install/enable mod_env, if not done yet. Then you create a new enviornment variable. I only tested it in the global apache-config, but it can probably also work for single virtualhosts:
<IfModule env_module>
    SetEnv environment development
</IfModule>
After reloading apache, you can now simply check for the environment in your bootstrap file:
<?php
if (isset($_SERVER['environment']) && $_SERVER['environment'] === 'development') {
    define('APPLICATION_ENV', 'development');
} else {
    define('APPLICATION_ENV', 'production');
}
I hope that this will be helpful for some of you.

Comments to this article

  • Avatar of Romeo Adrian Cioaba Reply Romeo Adrian Cioaba Wednesday, March 25, 2009 2:07 PM

    Just as a reminder, you can easily enable mod_env using:

    <code>a2enmod env</code>

  • Avatar of Anto Reply Anto Friday, March 27, 2009 5:45 PM

    Great solution man!

  • Avatar of Muhammad Reply Muhammad Friday, March 27, 2009 9:36 PM

    Great technique!
    But I using this value in master config file.
    config.xml or config.ini

  • Avatar of Vladimir Reply Vladimir Wednesday, April 1, 2009 11:30 AM

    Das ist klug

  • Avatar of Jonathan Kushner Reply Jonathan Kushner Saturday, April 4, 2009 6:40 AM

    I've come across situations before where it was neglected to show within the server globals, however was accessible via getenv. I didn't investigate much as to why it was occurring, but added an or check against getenv !== false (not null, but false) for that variable.

Leave a comment

Please note that your email address will not be shown, it is only used to fetch your avatar image from gravatar.com and for notifications.

             _           __       
  __ _  __ _| |__   ___ / _| __ _ 
 / _` |/ _` | '_ \ / _ \ |_ / _` |
| (_| | (_| | |_) |  __/  _| (_| |
 \__, |\__,_|_.__/ \___|_|  \__,_|
    |_|