0

Host based PHP settings

Posted July 18th, 2011 in Php by Florentin

How do you deploy a php settings file on multiple hosts which require different configurations ?
Let’s use the wp-config.php (WordPress configuration file) as an example.
The following snippets are going to be used inside your project’s config file (wp-config.php in this case)

Solution 1

1.a

if($_SERVER[‘HTTP_HOST’]==’example.com’ || $_SERVER[‘HTTP_HOST’]==’www.example.com’) {
# settings for the host example.com
} else {
# default settings
}

1.b

if(strpos($_SERVER[‘HTTP_HOST’], ‘example.com’)!==false) {
# settings for example.com
} else {
# default settings
}

If you need to define settings for multiple hosts, use a "switch" statement instead of "if"

Instead of "HTTP_HOST" one can also use "SERVER_NAME"

Alternatively to HTTP_HOST one can set the following in the apache’s virtual host
SetEnv APPLICATION_ENV "development"
then check for $_SERVER[‘APPLICATION_ENV’]

Pros
- light on the CPU and no disk access

Cons
- only works when the PHP file (wp-config.php in our example) runs though a web server environment, i.e. $_SERVER[‘HTTP_HOST’] is available.
- all settings live in the same file, if the file is added to a version control system everyone can view those settings.

Running the code though command line won’t work as expected.

Solution 2

if($_SERVER[‘REMOTE_ADDR’]==’127.0.0.1′) {
# localhost settings, host1
} else {
# any other settings, host2
}

Cons
- only works for 2 hosts, a localhost host (host1) and a remote host (host2)
- the settings for the host considered remote (host2) only work when the visitors come from a non-local IP.
If one uses SSH or VCN to access the remote machine (host2) then load the site/script locally, the host1’s settings will get loaded.

Solution 3

Create a file named "wp-config-local.php" in the same directory as wp-config.php then add the following to wp-config.php

if ( file_exists( dirname( __FILE__ ) . ‘/wp-config-local.php’ ) ) {
# the current host’s settings
} else {
# default settings
}

Every host would then manage it’s own wp-config-local.php without the need to share it though a version control system.

Pros
- privacy, it remains private to the host’s users
- works fine even if the script is called though the command line

Cons
- disk access

Leave a Reply