How to: Support multiple production environments in CodeIgniter

Posted: 2009-01-29
Category: CodeIgniter

To get this working is very easy. Constants can be seen all the way through CodeIgniter and can be set almost anywhere. To keep things neat and logical we will put this code into application/config/constants.php.

For a simple 2 environment switch you can use the following:

define('ENV', strpos($_SERVER['SERVER_NAME'], 'local') !== FALSE ? 'local' : 'live');Or if you have more than the two environments:if(strpos($_SERVER['SERVER_NAME'], 'local') !== FALSE) { define('ENV', 'local'); } elseif(strpos($_SERVER['SERVER_NAME'], 'dev.') === 0) { define('ENV', 'dev'); } elseif(strpos($_SERVER['SERVER_NAME'], 'qa.') === 0) { define('ENV', 'qa'); } else { define('ENV', 'live'); }

That will match:

http://localhost/ = local
http://local.example.com/ = local
http://dev.example.com/ = dev
http://qa.example.com/ = qa
http://example.com/ = live

Now you can base your config on if(ENV == 'live'). This is helpful for setting the $active_group in database.php, runing caching for live only, displaying profiler and debug data for local/dev only and plenty more.

Comments

Gravatar
Jay

2010-04-25

Just wanted to thank you for this. Works like a charm! Thanks a lot

Gravatar
Tim Reynolds

2010-05-26

For your Grime Challenge try Tough Guy (http://www.toughguy.co.uk/) looked bloody hard work, as I watched, and its all for charity.

Gravatar
Denford Berriman

2010-07-09

Hey Phil.

Cheers for the work on cURL for codeigniter.

Now I just need to figure out why I have a 411 error... maybe another heineken will help

Gravatar
Martin

2010-09-09

Nice tip, just what I was looking for

Gravatar
Huglester

2010-09-23

Awesome post. thank you
I saw some of this integration in PyroCMS, but didn't think it's so easy

Good job Phil:)

Gravatar
Ji Zhang

2010-12-22

Cheers for the work of cURL CI Lib , it is great piece,

happy XMS

Gravatar
Damon

2011-02-06

This also works well. You can add/remove as many dev. environments you need pretty easily.

switch(getenv('HTTP_HOST'))
{
case 'local.yoursite.com':
// local config settings here
break;
case'dev.yoursite.com':
// dev config settings here
break;
default:
// production settings here
}

Gravatar
Alon

2011-02-21

Hi Phil,

10x for this great Blog, it helps me a lot,
about 2010 objectives, I am still waiting for you in Thailand...

Gravatar
Usman

2011-06-14

Nice article. Really useful. I wanted to see how I could do this for a development/staging and live set up.

Posting comments after three months has been disabled.