Wednesday, December 12, 2012

PHP configuration files by environment

Ever want to define a configuration file for your code that is different on each of your servers automatically?

At bare minimum you may want to create a configuration file for your local development environment and your live server.

If you aren't using a framework like symfony or codeigniter and you'd like an easy way to make your configurations solid, then here is the trick for you.

It all comes down to defining a custom variable in the php ini file on your local environment. Simply open up your php.ini file, toss in the below code in there just below the [PHP] tag

server_environment = "local"

Then it's up to your programming to read this variable to decide what configuration to include. I use a general file named conf.php that gets included in my base controller class.

conf.php defines some pretty standard things like database connection strings, a site notification email address, and sometimes path information.

define('COOKIE_SALT','81234SupPotato99!!');


$server_environment = get_cfg_var('server_environment');
if ( $server_environment && file_exists(dirname(__FILE__). '/conf.'. $server_environment .'.php') ) {
include dirname(__FILE__). '/conf.'. $server_environment .'.php';
} else {
define('BASE_WEB', '/');
define('NOTIFY_EMAIL','email@email.com');

$db_config = array(
'username' => 'codebase',
'password' => 'zigzag',
'database' => 'codebase',
'host' => 'localhost',
'debug' => false,
);
}


Then you can create a file in the same folder as your conf.php file, name it conf.local.php and then you can define separate configuration parameters in there:


define('BASE_WEB', '/development/website/');
define('NOTIFY_EMAIL','email@anotheremail.com');

$db_config = array(
'username' => 'codebase',
'password' => '',
'database' => 'codebase',
'host' => 'localhost',
'debug' => true,
);

It's as easy as that, now you have a configuration file that will automatically be included for your local development environment with different parameters from your production configuration file.

If you need global configuration that applies to both your production and local environments, then just put the configuration parameters outside of your conditional statement in conf.php ( just like the cookie salt ).

No comments:

Post a Comment