One of the things that I absolutely love about CodeIgniter is the ability to use it with the command line. It seems like every site or application I write has a need for a cron job, and I find that by writing a writing a new cron controller that can be executed from the command line and leveraging the existing pieces of code that I have already written saves time and effort.
So, there is not much to do if you’re looking to leverage CodeIgniter in a CLI interface; however, there do seem to be a few gotchas that you need to be aware of. The CLI capabilities are built into CodeIgniter 2.0.1, if you have a previous version, you’ll need to download some additional libraries; or upgrade to a newer version of CodeIgniter.
First, you need to ensure that your $config[‘uri_protocol’] property from your config.php file is properly set. If it is set to ‘AUTO’ you’re good to go, you can automatically begin calling your CodeIgniter code from the command line; however, if it is set to anything other than ‘AUTO’ you’ll need to make some adjustments to the value of that property. For instance if you use the ‘PATH_INFO’ protocol, you’ll check to ensure that the $_SERVER[‘REQUEST_URI’] is set, before determining the protocol to use as shown below. If the $_SERVER[‘REQUEST_URI’] property is not set, you’ll instruct CodeIgniter to use the CLI interface.
/* Set to 'AUTO' */ $config['uri_protocol'] = 'AUTO'; /* Anything But 'AUTO' */ $config['uri_protocol'] = isset($_SERVER['REQUEST_URI']) ? 'PATH_INFO' : 'CLI';
Second, you just need to understand how to execute your calls to your CodeIgniter application from the command line. This is actually pretty simple, and can be done relatively easily. To execute your code from the command line use the following example template as shown in the source below:
/path/to/php index.php controller method param1 ...
Of course you’ll need to make the appropriate replacements in the command line call.
- Replace ‘/path/to/php’ with the absolute path to your php executable.
- Ensure ‘index.php’ is the absolute path of your CodeIgniter index.php file.
- Replace ‘controller’ with the name of the controller you’ll be calling.
- Replace ‘method’ with the controller method you’ll be calling.
- Replace ‘param1’ with any parameters that your controller method needs to execute, separated by a space.