Auto detect internal/external development environment
We use the following function to auto detect if we are on a machine internally or on a live server and then choose the appropriate configs for various components:
开发者_运维问答function devIsLocal(){
$res=false;
$http_host=$_SERVER['HTTP_HOST'];
if($http_host=='localhost')$res=true;
if($http_host=='127.0.0.1')$res=true;
if(substr($http_host,-4)=='.lan')$res=true;
if(strpos($http_host, '.')===false)$res=true;
return($res);
}
As you can see it only relies on the HTTP_HOST value.
Of course, if you use some sort of virtual host locally like example.com then the function will be tricked.
Are there any other ways to fool the function? and what other variables/places could we peek at to determine where we are?
Set an environment variable in your Apache virtual host configuration. This is the way the Zend Framework does it.
See the ZF quick start guide for an example (the "Create a Virtual Host" section.)
In your httpd.conf or a .htaccess file, put:
SetEnv APPLICATION_ENV "development"
Then in your application, use the getenv function to get the value:
$environment = getenv("APPLICATION_ENV");
if ($environment == "development")
{
// do development stuff
}
else if ($environment == "live")
{
// do live stuff
}
'127.0.0.1' == $_SERVER["REMOTE_ADDR"]
This will never evaluate as TRUE
on your live system. :)
Adding to Andy Shellam's answer..
If you are using mod_vhost_alias, or have various domains with the same (virtual) document root, you can set the variable dependent upon parameters, e.g.
SetEnvIf SERVER_ADDR x.x.x.x APPLICATION_ENV=development
SetEnvIf HTTP_HOST abc.example.com APPLICATION_ENV=development
Create and later look for a file that only exists on the live server's filesystem.
Granted, your environments should be as similar as possible; what I'm suggesting is something like this: in directory /var/environment/, have a file named {devel|test|qa|staging|live}, depending on the server you're on - then just check the filename.
Of course, you need to exclude this file from version control and from whatever build process you may have.
Of course, if you have use virtual host locally like example.com then the function will be tricked.
Also if the host is not local but uses a widlcard or default vhost defn and the user adds the IP address to the hosts file locally.
I would recommend having a directory on the include path which also exists on live but is not replicated there - and simply store:
function getEnv(){
return 'Live';
}
or
function getEnv(){
return 'Test';
}
If both envs are on the same server - you can still do this by setting the include_path in Apache config or .htaccess.
This also allows you to seperate potentially sensitive env specific data - like database hosts/passwords and encyption keys.
C.
精彩评论