Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solution to multi server environment with a CodeIgniter website

Tags:

codeigniter

I have a local, staging and production environment for my CodeIgniter based site. Increasingly I find everytime I deploy a version I have more and more little bits of code to change because of server variations.

What would be a good (and quick) solution I could add that would allow me to set these variables by just using one setting. Where would be the best place to insert this in the index.php, some sort of hook?

like image 881
Alex Avatar asked Sep 03 '26 02:09

Alex


2 Answers

If you're using Apache, you can set an environmental variable which can be read by PHP in your Virtual Hosts file for the site:

<VirtualHost *:80>
    DocumentRoot /path/to/site
    ServerName local.mysite.com
    ErrorLog /path/to/error_log
    CustomLog /path/to/access_log common
    <Directory /path/to/site>
        SetEnv ENVIRONMENT local
        RewriteEngine On
        Options FollowSymLinks Indexes
        AllowOverride AuthConfig Options FileInfo
    </Directory>
</VirtualHost>

So with that, you now can check for and set the server environment accordingly in your index.php file:

// always default to production for safety
$environment = 'production';

// check for an environment override
if (function_exists('apache_getenv') && apache_getenv("ENVIRONMENT")) {
  $environment = apache_getenv("ENVIRONMENT");
} else if (getenv("ENVIRONMENT")) {
  $environment = getenv("ENVIRONMENT");
}

// set the environment constant
define('ENVIRONMENT', $environment);

With this setup, you now have the freedom to deploy your sites and add additional configuration parameters to your application/config/[file].php files for each environment.

Alternative...

Another possibility for handling multi-environment setups is to create a file outside of the document root and is ignored by your version control system (i.e. .gitignore) which contains the value of the server environment. You could then just read that file via file_get_contents() or equivalent.

like image 100
Corey Ballou Avatar answered Sep 07 '26 10:09

Corey Ballou


define a "LIVE" constant which is TRUE or FALSE based on the current domain its on (put this in your index.php file)

if(strpos($_SERVER['HTTP_HOST'], 'mylivesite.com'))
{
    define('LIVE', TRUE);
}
else
{
    define('LIVE', FALSE);
}

and then check to see if you are live or not and assign the variables accordingly

if(LIVE)
{
    $active_group = "production";
}
else
{
    $active_group = "test";
}

ive been doing this with our 5 environment setup for the past year with no problems

like image 21
Tom Schlick Avatar answered Sep 07 '26 08:09

Tom Schlick