PHP: Identifying Production & Development Server

This is a short guide on how to write PHP code that identifies whether your application is running on a production server or a test / development server. More often than not, your application will have different configuration values for each server environment.

A few examples:

  • The MySQL server that is installed on your local machine will probably have different connection details than the MySQL server that you use on your production server.
  • File paths may be different.
  • The URL of your app will be different.
  • Your development environment may not support some of the services and daemons that are present on your production server.

More often than not, developers drive themselves crazy trying to change configuration files and whatnot before they deploy their code to the production server. Then, when they need to work on the codebase inside their development environment, they end up having to change all of these configuration values back again.

Here’s a very basic example that attempts to solve this issue:

<?php

/**
 * Our example configuration file.
 */

//Is this the production server or not?
define('PRODUCTION', true);


//Set the site URL.
if(PRODUCTION){
    //The URL of our live website.
    define('SITE_URL', 'http://example.com');
} else{
    //The URL that we use in our development enviornment.
    define('SITE_URL', 'http://localhost/example/');
}

//MySQL details.
if(PRODUCTION){
    define('MYSQL_SERVER', 'my12.mysqlserver.example');
    define('MYSQL_USERNAME', 'mu_2337823');
    define('MYSQL_PASSWORD', 'sh73hdhIEO!ndgh3903');
    define('MYSQL_DATABASE', 'db_273HSJ');
} else{
    define('MYSQL_SERVER', 'localhost');
    define('MYSQL_USERNAME', 'root');
    define('MYSQL_PASSWORD', '');
    define('MYSQL_DATABASE', 'my_db');
}

On some tutorials, I’ve seen people posing code that sets the PRODUCTION constant to FALSE if the value of HTTP_HOST is equal to “localhost”.

I mean, it looks simple and straight-forward, right?

//Is this the production server or not?
if($_SERVER['HTTP_HOST'] == 'localhost'){
    define('PRODUCTION', false);
} else{
    define('PRODUCTION', true);
}

Although the above PHP code looks like it might be a good solution – it really isn’t. Why? Because the client can change HTTP_HOST to any value that it wants to. This means that a malicious attacker could change HTTP_HOST to “localhost” and fool your application into thinking that it is running in a development environment – a dangerous thing if your app prints out debug information.

Another solution is to use environment variables, which are supported on both Windows and Linux. i.e. Create an environment variable for your development server and then check to see if that variable exists:

//Is this the production server or not?
if(isset($_ENV['DEV_ENVIORNMENT'])){
    define('PRODUCTION', false);
} else{
    define('PRODUCTION', true);
}

Hopefully, you found this guide to be helpful!