Skip to content

Instantly share code, notes, and snippets.

@aderowbotham
Created November 25, 2012 17:37
Show Gist options
  • Save aderowbotham/4144488 to your computer and use it in GitHub Desktop.
Save aderowbotham/4144488 to your computer and use it in GitHub Desktop.
PHP / Codeigniter - set environment when running in CLI mode
<?php
# in public_html/index.php
/*
* Where your CodeIgniter ENVIRONMENT is normally defined by the server environment
* variables, and assuming your database settings are automatically set based on
* that environment, this causes a problem when running the application through
* PHP on the command line e.g. in order to run CodeIgniter Migrations
*
* This can be solved by setting the environment from the $argv array.
* The following example for a testing environment would be called on the command
* line like this:
$ cd /path/to/public_html/
$ php index.php migrate testing
*/
if (PHP_SAPI === 'cli'){
if($argv[1] != 'migrate' || !isset($argv[2]))
exit("Access denied\n");
else
define('ENVIRONMENT', $argv[2]);
} else {
define('ENVIRONMENT', getenv('APPLICATION_ENV'));
}
# continue with index.php bootstrap
/*
* Note that in your migrate controller, you can restrict access to command line only as follows:
*
*/
if(!$this->input->is_cli_request())
show_error('Access denied',403);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment