开发者

Conditional configuration: How to detect if I'm local or online?

开发者 https://www.devze.com 2022-12-16 02:18 出处:网络
I want to provide different configurations for local and offline. At the moment, every time I upload my stuff to the web server, I must make sure that I don\'t mess up with the different config files.

I want to provide different configurations for local and offline. At the moment, every time I upload my stuff to the web server, I must make sure that I don't mess up with the different config files. One for local development, and one for online.

I slightly remember a couple of years ago, a code snippet distinguished somehow automatically between online and local development.

Is there a safe way 开发者_开发技巧to detect that?


I generally use the server name, for that ; for example, here's what I use on my blog :

if ($_SERVER['SERVER_NAME'] === 'blog') {
    // Development
} else {
    // Production
}

This is because :

  • On my development machine, the blog is accessed via http://blog (nothing else after), using a VirtualHost with a ServerName directive.
  • On the production server, of course, the ServerName directive is a bit longer than this, containing the actual blog server name.


I have build this function that checks if current server name has name server records, normally local server don't has.

<?php
function isLocal ()
{
  return !checkdnsrr($_SERVER['SERVER_NAME'], 'NS');
}
?>


Another approach: Set up a .htacces file in your development root:

SetEnv APPLICATION_ENV development

Then read it:

defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV')
                                    ? getenv('APPLICATION_ENV')
                                    : 'production'));


My answer is basically the same as Pascal’s on this page, but since you may change your development server name and you may need several of this checks in your code, i prefer doing this:

define ('DEV_HOST', 'blog'); // if you just use http://blog locally

And then check

if ($_SERVER['SERVER_NAME'] == DEV_HOST) {
  // do your tricks
}


Here is a solution that requires zero configuration and should work pretty fast:

function isOnline()
{
    return checkdnsrr('google.com', 'ANY');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消