Skip to content

Instantly share code, notes, and snippets.

@yeondudad
Last active August 29, 2015 14:20
Show Gist options
  • Save yeondudad/b3941b7c021822b834ac to your computer and use it in GitHub Desktop.
Save yeondudad/b3941b7c021822b834ac to your computer and use it in GitHub Desktop.
Changeable configuration in php
<?php
global $conf;
if (!isset($conf)) {
$pathTemplate = dirname(__FILE__) . '/conf_%s.php';
$configFile = sprintf($pathTemplate, 'script');
$currentConfigFile = sprintf($pathTemplate, gethostname());
if (file_exists($currentConfigFile)) {
$configFile = $currentConfigFile;
} elseif (array_key_exists('HTTP_HOST', $_SERVER)) {
$currentConfigFile = sprintf($pathTemplate, $_SERVER['HTTP_HOST']);
if (file_exists($currentConfigFile)) {
$configFile = $currentConfigFile;
} else {
$configFile = sprintf($pathTemplate, 'localhost');
}
}
$conf = require $configFile;
}
return $conf;
<?php
return array(
"conf_key" => "this is localhost."
);
<?php
return array(
"conf_key" => "this is script."
);
<?php
return array(
"conf_key" => "this is test.com."
);
<?php
$_SERVER['HTTP_HOST'] = 'localhost';
$conf = require 'conf.php';
echo $conf["conf_key"]; // this is localhost.
<?php
$conf = require 'conf.php';
echo $conf["conf_key"]; // this is script.
<?php
$_SERVER['HTTP_HOST'] = 'test.com';
$conf = require 'conf.php';
echo $conf["conf_key"]; // this is test.com.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment