WARNING

We discovered (to our cost) that this technique is fine for a Drupal site where you maintain the modules via FTP, but if you happen to use Drush, this technique has a major disadvantage; Drush doesn’t parse the if-then-else statement, and so picks up the last set of database settings in this file. So your Drush updates – which you thought were affecting your development site only – have actually just taken place on the live site. Because of this, we no longer recommend this technique, but we’ve left the post in place so that search engines which have already indexed this page will be able to pick up this warning.

The original post..

It’s very common for us to have a live site for public viewing, and a development site where we’re adding new content, testing new layouts or whatever. More than once, we’ve been caught out by copying the wrong settings.php file across, so suddenly the live site is running from a development database – not a nice situation to be in!

Our solution to this is the creation of a settings.php file which can automatically detect which domain it’s being called from, and then link into the appropriate database. Sounds clever, but it’s actually quite simple;

if(stristr($_SERVER['SERVER_NAME'], 'dev.') !== FALSE) {
 // We are running on the test server
 $db_url = 'mysql://testdnname:testdbpassword@127.0.0.1/testdb';
 $cookie_domain = 'dev.testsite.com';
 $conf = array(
 'site_name' => 'TEST Server - Development site',
 );
 }
else {
 // We are running on the live server
 $db_url = 'mysql://livedbusername:livedbpassword@127.0.0.1/livedb';
 $cookie_domain = '.liveserver.com';
 $conf = array(
 'site_name' => 'Live Server Name',
 );
}