Skip to content

CodeIgniter from the Comand Line

So the question is “How do I write command line applications that use CodeIgniter?” Well, my techie friends, it’s incredibly easy!

First create a directory to hold your command line scripts. Here’s what my directory structure looks like:

- / <-- This is my project root
    + application/
    + htdocs/
    + tools/ <-- Here's where I put my command line scripts

Now we create a tiny script to run our code. It doesn’t matter what you name it since the only reference to it will be as a command line argument to the php interpreter. I named mine rssBuilder.php. Here’s the entire contents of that script: set_time_limit(0); $_SERVER['PATH_INFO'] = '/rssbuilder/personal'; require_once '../htdocs/index.php';

The first line of code tells the PHP interpreter to let the script execute for an unlimited amount of time. This is necessary for many command line scripts.

The second line tells CodeIgniter to use the personal() method of theRssbuilder controller. You will build the controller as you would any other controller. $_SERVER[‘PATH_INFO’] is usually supplied by php when a web request is made. However, since we are calling this script from the command line, we need to emulate this small part of the environment as a web request.

The last line includes the CodeIgniter index.php file which sets up the CodeIgniter environment. This is the same old index.php file that lives in the document root of your site.

One important note about using CodeIgniter from the command line is that if you want your controller to only be accessible from the command line and not the web, you should place this small piece of code at the top of your controller: if($_SERVER['SCRIPT_FILENAME'] != 'rssBuilder.php') { header('location: /'); // Ideally, send a 404 error instead of redirect. exit; }

You can use views. The Rssbuilder controller uses an xml view but assigns the output to a variable and writes that output to a file. By setting the third parameter of view() to true, the method will return the results of the parsing as a string instead of outputting to the ‘browser’ or in this case, the standard output stream (stdout). Here’s how I call the view() method: $myFeed = $this->load->view('rss.xml', $data, true);

Now, all that’s left is to call the script from the command line with the php interpreter.php rssBuilder.php

And that’s all there is to it! I hope this helps you out and saves you some time!



Published inWeb Development

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *