af83

Switch configurations for a PHP script based on the virtual host, taking into account the console and proxies

Sometimes (often) you would want your script to have different configurations based on the environment in which it runs (dev, test, prod). Sometimes the same script may even be run from the console and you really want to have a different configuration for that. Now you may run into some trouble using just the $_SERVER["HTTP_HOST"] variable. Even more so if you are running behind an proxy (such as mod_proxy for apache).

Here is a small snippet that will help you cover almost every instance… and tell you what is the execution context of the script so you can change the db setup, turn on or off the debugging etc…

Note that in this case the $vhost here may very well contain a list of hosts separated by commas.

if ((isset($_SERVER["SESSIONNAME"]) && $_SERVER["SESSIONNAME"] =="Console") || (isset ($_SERVER["TERM"])))
{
    $vhost="console";
} else
    {
    if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])){$vhost=$_SERVER["HTTP_X_FORWARDED_HOST"];}
        else
            {
            if (isset ($_SERVER["HTTP_HOST"])) $vhost = $_SERVER["HTTP_HOST"];
                else
            $vhost = $_SERVER["SERVER_NAME"];
            }
    }
switch($vhost){
    case 'myproductionhost.com':
        //setup configuration
    break;
    case 'myproductionhost.com, someotherhostusingmodproxy.com':
        //setup configuration
    break;
    case 'mytesthost.com':
        //setup configuration
    break;
    case 'console':
        //setup configuration
    break;
    case 'locahost':
        //setup configuration
    break;
    }

blog comments powered by Disqus