Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 935
zaf Avatar asked Apr 09 '10 11:04

zaf


3 Answers

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
}
like image 104
Andy Shellam Avatar answered Nov 07 '22 06:11

Andy Shellam


'127.0.0.1' == $_SERVER["REMOTE_ADDR"]

This will never evaluate as TRUE on your live system. :)

like image 12
fuxia Avatar answered Nov 07 '22 07:11

fuxia


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
like image 3
cEz Avatar answered Nov 07 '22 07:11

cEz