Multipurpose PHP Config Files

Published 16 September 04 by Justin French, 2 comments

How many times have you uploaded the new update for a website or web application, and accidentally overwritten the live config file with your dev one? Too many times to count in my case, and version control on the two files is also a pain.

Eventually I figured out a simple way of using the same config file in two places at once. It’s so obvious that I’m sure many have done it before me, but I’ve never seen it documented.

First things first, we need to determine if we’re on the live server or the dev server. In my case, it’s as simple as checking if the phrase “localhost” can be found in the server name. You could also check for a certain IP address, OS platform, etc.

<? 
$live = (eregi("localhost",$_SERVER['SERVER_NAME'])) ? 0 : 1;
?>

Then we can use PHP’s shorthand if/else control structure to specify a dev and live value for each configuration directive in one file. Each line has this format:

<? 
$name = ($live) ? 'live value' : 'dev value'; 
?>

Of course, for values that are the same in both environments, you can just use a basic variable declaration.

<? 
$name = 'shared value'; 
?>

Here’s an example config file:

<?
// are we live or dev?
$dev = eregi("localhost",$_SERVER['SERVER_NAME']);
// some config directives
$dbhost = 'localhost';
$dbname = ($live) ? 'cat' : 'dog';
$dbuser = ($live) ? 'justin' : 'root';
$dbpass = ($live) ? 'secret' : 'squirrel';
$debug = ($live) ? 0 : 1;
$docroot = ($live) ? '/path/to/docroot' : '/path/to/docroot';
// what about some PHP directives?
$errors = ($live) ? E_NONE : E_ALL;
error_reporting($errors);
?>

Hopefully this will save you from ever having to maintain two config files for live and dev use, and you’’ never have to worry about overwriting the live config file again.

For those of you wondering where you’d use this, it works great with Textpattern’s config file.

Note: Yes, I chose the familiarity of eregi() over the faster, but lesser-known strpos() – you can take your pick.

Update: See Multipurpose PHP Config Files Revisted for a few nice modifications and updates on this.

Options

What is this?

portrait of Justin

This is the online home of Justin French, a designer & web application developer located in Melbourne, Australia. I like finding ways to make things work better. I like clarifying and simplifying. I like to understand how you understand things.

» read more

Subscribe to my feed

Follow me on Twitter

@justinfrench

More Notebook Articles

Show more notebook articles

Search