Archive for May 18th, 2007

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.

PHP:
  1. if ((isset($_SERVER["SESSIONNAME"]) && $_SERVER["SESSIONNAME"] =="Console") || (isset ($_SERVER["TERM"])))
  2. {
  3.     $vhost="console";
  4. } else
  5.     {
  6.     if (isset($_SERVER["HTTP_X_FORWARDED_HOST"])){$vhost=$_SERVER["HTTP_X_FORWARDED_HOST"];}
  7.         else
  8.             {
  9.             if (isset ($_SERVER["HTTP_HOST"])) $vhost = $_SERVER["HTTP_HOST"];
  10.                 else 
  11.             $vhost = $_SERVER["SERVER_NAME"];
  12.             }
  13.     }
  14. switch($vhost){
  15.     case 'myproductionhost.com':
  16.         //setup configuration   
  17.     break;
  18.     case 'myproductionhost.com, someotherhostusingmodproxy.com':
  19.         //setup configuration
  20.     break;
  21.     case 'mytesthost.com':
  22.         //setup configuration
  23.     break;
  24.     case 'console':
  25.         //setup configuration
  26.     break;
  27.     case 'locahost':
  28.         //setup configuration
  29.     break;
  30.     }

Click to continue reading

Creative Commons License
This work is licensed under a Creative Commons Attribution 2.0 License.