in PHP

Considering local, dev and live environments

When you develop a website for a client you should usually be considering three or even four (if you also include staging) environments where one code base may be used. Local, development and live.

In this case you may want the code to behave slightly differently depending on where it’s being used.

A good example I regularly come across is when and where to send any emails that a system generates. When you are testing locally or on a development server you certainly don’t want to send out emails to people who have no knowledge of the system.

The first thing I do is include a quick check to see where the code is being used in a config file:

if(preg_match("@^/folder/path/harrybailey/site@", $_SERVER['DOCUMENT_ROOT'])){
	define('LOCAL', true);
	define('DEV', false);
	define('LIVE', false);
} elseif(preg_match("@^/another/path/hosting/site@", $_SERVER['DOCUMENT_ROOT'])) {
	define('LOCAL', false);
	define('DEV', true);
	define('LIVE', false);
} elseif(preg_match("@^/final/path/somehosting/site@", $_SERVER['DOCUMENT_ROOT'])) {
	define('LOCAL', false);
	define('DEV', false);
	define('LIVE', true);	
} else {
	die('Unknown host');

I can now do simple checks anywhere across my site to see if I want to carry out certain tasks, or use different messages when notifying the user of their actions.

if(DEV) {
	// send email to the creator instead of the new user
	$message = 'Because this is a test server we will send the email to you, not ' . $to;
	$to = $Creator->email_address;

It has many used, but using constants across a development makes environment specific code easier to handle.

Although I’ve written the code above in php, it’s easily transferred to any language.