Wednesday Jun 19
Nov
28/12
Setting Environment Variables for PHP Using Apache
Last Updated on Wednesday, 28 November 2012 05:35
Written by Cody Snider
Wednesday, 28 November 2012 05:35

If you’re working in a setup where production machines and development machines are doing slightly different thing (DB connection details, debugging, etc…) then you’ll likely need so way to set a variable to determine which environment the application is in. To keep it out of the application code itself and out of repositories, I’ve always preferred setting an environment variable in Apache’s httpd.conf and accessing it through PHP. Here’s how that’s done.

Open your production httpd.conf and add a line following the example below. This will set the flag. Note that this can also be done in the .htaccess file to get the same effect.

SetEnv HTTP_CODE_ENV "production"

You can do the same in your development environment (or, even safer than this is to default to production settings and only set this in development).

SetEnv HTTP_CODE_ENV "development"

Now, to access this in PHP, just use the following snippet early in your call stack (the bootstrap, for example).

define('ENVIRONMENT', $_SERVER["HTTP_CODE_ENV"]);

From this point forward, you can access the string from httpd.conf anywhere in PHP as the constant defined above.


2 Comments
  1. Commentsr2_   |  Thursday, 29 November 2012 at 10:35 am

    A sane default for database configs is an error. IMO, defaulting to production is asking for trouble.

  2. CommentsCody Snider   |  Thursday, 29 November 2012 at 2:54 pm

    I think we agree on this for the most part. The reason I choose to default out to production is due to the fact that configurations will often have potentially sensitive details in error reports and, in the event that a machine running the application is missing the correct settings to determine environment and configuration, it is best to err on the side of caution and fall back to production settings.

    The result should be the same if the development/staging/QA machines and production don’t use the same database connection details. A connection error will occur (though I think you’re saying the application itself says, “Whoa, the environment isn’t set! Fix that.”).


Leave a Reply






Buy me a beer

What better way to say you love the article than a cold, refreshing beer? Cheers. :-)

    • Software engineer from NYC proficient in PHP, Python, HTML, CSS, Javascript and AS3.