Simple Staging Server

This isn't a PHP-specifc article, but is relevant to programming in PHP.

Sometimes, you'll find that the site you're working on has absoulte URLs. Maybe it's in the HTML, or, just as likely, you're using a feature, like redirection, that requires specifying a domain name.

There are several ways to adapt your code to operate on two different computers, so you can have one copy of the code on a development machine, and another copy on the live server. One quick trick that can work is to use /etc/hosts to direct requests for your live site over to your local server.

/etc/hosts is a file on your computer (assuming you have a Unix box at home) that maps IP addresses to domain names. It looks like this:

127.0.0.1 localhost localhost.localdomain

When I'm working, I will add a couple entries to /etc/hosts to point my domains back to my local development machine.

127.0.0.1 localhost localhost.localdomain
127.0.0.1 www.riceball.com
127.0.0.1 riceball.com

Apache's configured to have virtual hosts for these two domains.

Within the code, I do a simple detection to adjust my variables:

if ($_SERVER['SERVER_NAME']=='stage') {
    $dbhost = '127.0.0.1';
    $root = '/home/johnk/Sites/riceball.com';
}

This code automatically switches a couple global values so that the software will work with my staging environment. Usually, you can get away with switching only two or three values.

The main "problem" with this technique is that it can make it difficult to upload files to the server. You have to undo the changes to /etc/hosts. Then, relaunch the FTP client, and upload. This can be a pain, but most of the time, you should finish coding, and testing, and committing code to the repository, before uploading. In other words, upload infrequently.

The following is a script to automate switching between two different /etc/hosts files. It must be run as root.

#!/bin/sh

# swaps out two /etc/hosts files, for staging purposes.

cp /etc/hosts /etc/hosts.swap1
mv /etc/hosts.swap /etc/hosts
mv /etc/hosts.swap1 /etc/hosts.swap

cat /etc/hosts

There is one significant deficiency of this system, in that the staging environment is inaccessible to anyone but the lone developer. A more elaborate setup can be used to stage software on a LAN, however, people outside the LAN won't be able to easily access the servers. It's not a one-size-fits-all solution.

If you're on a LAN with a router that has been reprogrammed to use OpenWRT, you can try the technique described in Simple Staging LAN. It works like the above, but on the entire network, for all operating systems.