Add to Favorites

PHP on go the go - configuration script trick

Do you ever take your work home? Do you just use a copied version of your code base or checkout from subversion to work on a separate computer? Well then, you too will have experienced the multiple configuration file annoyance.

Some web specific frameworks like ruby on rails use a system to define different environments, then use different configuration files for the different environments. In php, if you are not using a framework, you may think you are stuck to swapping out configuration files or changing the conf file when you take the code home. This is not so, I will now share with you a trick to remove this annoyance from your life.

[code]

$base_conf = get_cfg_var('server_environment');
if ( $base_conf && file_exists(dirname(__FILE__). '/conf.'. $base_conf .'.php') ) {
include dirname(__FILE__). '/conf.'. $base_conf .'.php';
} else {

standard confiugration stuff

}

[/code]

This code checks for the "server_environment" in your php.ini file, then checks the directory that this configuration file was found in, to see if conf.<server_environment>.php exists.

In your php.ini file at home, define server_environment to be a a value such as "home" in your php.ini file somewhere. Then take the normal conf.php file and copy it to conf.home.php in the same spot as your conf.php file. Make sure however that the conf.home.php file does not have the code to check server_environment, otherwise you will create an infinite loop of inclusion and your php code will not work.

With this trick, you can now just checkout or copy code for home and never again swap configuration files between the two environments.

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up