开发者

localhost/live - detect by HTTP_HOST

开发者 https://www.devze.com 2022-12-28 16:56 出处:网络
let\'s say I develop locally and debug small things on live server. Is it good idea to have something like this in my code? :

let's say I develop locally and debug small things on live server.

Is it good idea to have something like this in my code? :

$is_local = (strpos($_SERVER['HTTP_HOST'], 'localhost') !== false);
define ('DEBUG',$is_local);

And then use it through my code, when setting stuff?

$mysql_settings = (DEBUG) ? 
  array(/*localhost settings*/) : 
  array(/*live settings*/);

This way, I can use the same files live and on localhost, so I can sync without any fear of having wrong e.g. 开发者_如何学Cconnection settings on live server.

Is it good or wrong idea?


Nothing at all wrong with doing the way you're doing it.

Another strategy is to set up some environment variable on your development (or other, non-production) system.

Under apache, you could stick something like this:

SetEnv MYAPP_ENVIRONMENT development

in httpd.conf or a suitable .htaccess file

Then in your configuration code:

if (! getenv('MYAPP_ENVIRONMENT')){
  $env = 'production';
}else{
  $env = getenv('MYAPP_ENVIRONMENT"));
}

require_once 'conf/config.' . $env . '.php';

or something along those lines.


IMHO, what you're doing isn't that bad at all.

The only flaw is on the $is_local line:

$is_local = (strpos($_SERVER['http_host'], 'localhost') !== false);

This could evaluate to TRUE for a site like localhostIsAwesome.com.

Overall, though, the way you are doing it is actually pretty decent.

One other suggestion would be to use $_SERVER[ 'SERVER_NAME' ]


it's not a bad idea, if

  1. you have only two environment, local and server
  2. you never have to turn on the debug mode for the server

so it does not address scenario like

  1. multiple environments like dev, test, production
  2. team of more than two developers

A practice I employ on a project is to have settings code files like conf.dev.php, conf.test.php, conf.prod.php for different environment settings, and one file for env switch flag like

$env = 'production';

then you can include file containing the env setings dynamically based on the $env switch, like:

require_once 'conf.'.$env.'.php';

remember to include the conf.dev.php file in git/hg/svn ignore file, so it will not mess up among team members, and conf.production.php in ignore file too for security reason.

just my two cents.

0

精彩评论

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

关注公众号