CodeIgniter for Rapid PHP Application Development

5 (1 reviews total)
By David Upton
  • Instant online access to over 8,000+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introduction to CodeIgniter

About this book

CodeIgniter (CI) is a powerful open-source PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. CodeIgniter is an MVC framework, similar in some ways to the Rails framework for Ruby, and is designed to enable, not overwhelm.

This book explains how to work with CodeIgniter in a clear logical way. It is not a detailed guide to the syntax of CodeIgniter, but makes an ideal complement to the existing online CodeIgniter user guide, helping you grasp the bigger picture and bringing together many ideas to get your application development started as smoothly as possible.

Publication date:
July 2007


Chapter 1. Introduction to CodeIgniter

Most of us just want to write applications that work well, and to do it as simply and easily as we can. This book is about CodeIgniter, a tool for making PHP easier to use.

If you need to produce results, if you think that the details and intricacies of coding are for geeks, then you should look at CodeIgniter (CI to its friends).

CI is free, lightweight, and simple to install, and it really does make your life much easier. Just read this chapter to find out how:

  • What CI can do for you

  • What is a 'framework' and how does CI fit in?

  • The open-source business model

  • Some disadvantages of CI (no, it's not perfect)


What can CodeIgniter Do for You?

If you are already writing code in PHP, CodeIgniter will help you to do it better, and more easily. It will cut down on the amount of code you actually type. Your scripts will be easier to read and update. It will help you to give large websites a coherent structure. It will discipline your coding and make it more robust, in some cases without you even knowing it.

That's quite a big claim. You have already spent some time learning PHP, HTML, CSS, a database, and several other acronyms' worth of geek speak. You need a basic, but not necessarily an expert, knowledge of PHP to benefit from CI.

CodeIgniter is not for you if:

  • You don't have a reasonable knowledge of PHP and HTML.

  • You want to write a basic Content Management System (CMS) quickly and simply, with a minimum of coding. (Look at a product like Expression Engine.)

  • You only want to write simple websites with a few standard features.

Save Time

CI doesn't take long to learn, and it quickly pays for your effort in the time saved later on. Let's look at a simple measure:

How CI cuts down the amount of code you need to type.

This is not just good for the lazy. The less you type, the fewer mistakes you make, and the less time you spend debugging your code. The smaller your code is, the faster it loads and less space it takes up.

Here are two examples (which are explained later on in this book, so don't worry now about how they work!).

Imagine you are writing a database query. This is how you might write a function within your PHP programme to query a MySQL database:

$connection = mysql_connect("localhost","fred","12345");
mysql_select_db("websites", $connection);
$result = mysql_query ("SELECT * FROM sites", $connection);
while ($row = mysql_fetch_array($result, MYSQL_NUM))
foreach ($row as $attribute)
print "{$attribute[1]} ";

Now see how a CI function would handle a similar query:

$query = $this->db->get('sites');
foreach ($query->result() as $row)
print $row->url

Compare the character counts: 244 for the traditional syntax; 112 for CI.

Now let's imagine that you are writing a data entry form in HTML, and you want a drop-down query box. Let's say this drop-down query box shows three options and allows the user to select one of them. In HTML, a drop-down box can be created like this:

<select name="type"> <option value="1"></option> <option value="2"></option> <option value="3" selected></option> </select>

CI's version is both shorter and, because it works from an array, more adapted to PHP processing:

$urlarray = array( '1' => '', '2' => '', '3' => '', ); $variable .= form_dropdown('url', $urlarray, '1');

In HTML, you need to type 154 characters; in CI, 128.

Make Your Site More Robust

Although you don't need to write as much code, CI provides a lot of the standard functionality for you, and remembers all those oddities and quirks. It keeps track of things you may have forgotten all about. (Those little touches that distinguish amateur sites from professional ones…)

Keep Your Links Up-To-Date Automatically

Imagine that you've just written a menu page, with lots of hyperlinks to other pages in your site. They are all in the traditional HTML format:

<a href="">say hello to Fred</a>

Then, you decide to move the site to another URL. That means you have to go painstakingly through your code, looking for each URL, and re-writing it, or else none of your links will work.

CI gives you a simple function to write hyperlinks like this:

echo anchor(start/hello/fred, Say hello to Fred);

CI also encourages you to put the URL of your site in a configuration file that the rest of your site can access. CI's anchor function that we've used here automatically refers to that configuration file. So, when you come to move your site, you only need to change that one entry in the configuration file, and all your hyperlinks update automatically.

Save Database Crashes: 'prep' Your Data Entry Forms

Data entry is fraught with problems. Because of limitations of HTML and databases, data that contain certain symbols— for example, apostrophes and quotation marks— may cause your database to crash or to give results you did not expect.

The answer to this is to prepare or 'prep' your data in your data entry form, before it is submitted to the database. All this takes time and a certain amount of extra coding.

CI's form helper does this, automatically. So, when you create an input box by typing:

echo form_input('username', 'johndoe');

You're also getting the hidden benefit of:

function form_prep($str = '')
if ($str === '')
return '';
$temp = '__TEMP_AMPERSANDS__';
// Replace entities to temporary markers so that
// htmlspecialchars won't mess them up
$str = preg_replace("/&(\d+);/", "$temp\\1;", $str);
$str = preg_replace("/&(\w+);/", "$temp\\1;", $str);
$str = htmlspecialchars($str);
// In case htmlspecialchars misses these.
$str = str_replace(array("'", '"'), array("'", "&quot;"), $str);
// Decode the temp markers back to entities
$str = preg_replace("/$temp(\d+);/","&\\1;",$str);
$str = preg_replace("/$temp(\w+);/","&\\1;",$str);
return $str;

This is code that handles special characters like '&'; so that they don't cause confusion while your form is being submitted. As you can see, there is some quite tricky regex code in there.

Possibly you like typing out regexes. Some people like lying on beds of nails, some like listening to ABBA; it's a free country. (Well, it is where I'm writing this.) But if you don't like these things, you can let CI do them for you (the regexes, I mean, not ABBA), and you needn't even be aware of the code that's working away in the background for you, every time you write that one simple line of code:

echo form_input('username', 'johndoe');

Make Your Code Bolder

CI also makes it easy to do things you might not have tried before. Of course, PHP users can always integrate libraries from PEAR and other sources, but these aren't always easy to integrate, or use, and their syntax and standards differ greatly. CI has a common set of standards, and once you've mastered its syntax, all its parts work together without complication. All its code is well-written and reliable, and is tested out by its user community. It puts much more sophistication in your hands.

Let's look at two examples to illustrate this point.

Send Email Attachments without Hassles

Sending emails is a complex business. CI's code for doing it looks easy to follow:

$this->load->library('email'); $this->email->from('[email protected]', 'Your Name'); $this->email->subject('Email Test'); $this->email->message('Testing the email class.'); $this->email->send();

There are a number of issues involved in sending emails: setting word-wrapping (and escaping it so long URLs don't get wrapped and broken up) for example, or sending attachments. The standard PHP functions can get quite complex here, and the result is that many code writers are tempted to avoid using these functions if they possibly can.

CI's email class makes it simple to send an attachment. You write:


CI does the rest. Working behind the scenes, for example, is a function that sorts out MIME types for nearly hundred different types of attachment. So it knows that your photo, photo1.jpg, is an 'image/jpeg' MIME type. It remembers to generate boundary delimiters in the right places around your attachments. It takes care of wrapping your text, and it allows you to easily mark out chunks of text you don't want wrapped.

Save Bandwidth by Zipping Files That Users Need to Download

To save bandwidth, it's a fairly common practice to compress or 'ZIP' files before you download them. That's not something I've ever done, and I wouldn't know how to go about it. On the other hand, CI has a nice facility that allows you to produce zipped files with four lines of code:

$name = 'mydata1.txt'; $data = 'the contents of my file…………'; $this->zip->add_data($name, $data); $this->zip->archive('c:/');

Run this, and you find a ZIP archive on your C drive containing one file. Your ZIP filer reader will unzip it and produce the original data for you.

People who use your site won't know that you've produced this impressive result so easily. They'll be impressed! Your site will save bandwidth. You did it in minutes rather than hours.


Yes, But…What is CodeIgniter? What are Frameworks?

Shortly after programming was invented, someone noticed that it involved many repetitive operations. And shortly after that, someone else—maybe it was Ada Lovelace, spanner in hand, adjusting Babbage's differential engine, or maybe it was Alan Turing at Bletchley Park—decided to modularize code, so you only had to write certain chunks once, and could then re-use them. PHP programmers are used to writing separate chunks of code in functions, and then storing those functions in include files.

At one level, a framework is just that: lots of chunks of code, stored in separate files, which simplify the coding of repetitive operations.

In the examples above, connecting to the database or building HTML form elements are abstracted and simplified for you. You call a function in the framework, which is easier to handle than the original code.

It goes beyond that. Writing code involves continuous choices between the many ways of tackling the same problem; so most frameworks also impose a set of choices on you. They've started to handle the problem one way, so you have to go that way as well. If these are sensible choices, this makes your life much simpler too. (If not, it's like trying to write a sales brochure using Excel, or do cash-flow projections using Word. Both can probably be done, but neither is the best use of your time.)

Sensible design decisions make sure that the things you need are accessible, but prevent them from spilling over into each other. A good framework makes those decisions for you, starting you off with a sensible foundation for your program and guiding you through the next steps.

Mention frameworks nowadays, and people think of Ruby on Rails.

Rails has become the success story of the last year or so, because it apparently offers effortless and rapid website development, with a minimum amount of coding. Essentially, it is a structure and a set of tools, built for use with the Ruby language, that allow you to build certain types of Ruby programs more quickly. It's not the only framework for Ruby, but it is very effective and, deservedly, very popular. On the other hand, if you have put in the time and effort to learn PHP, starting over again in Ruby is a long haul.

There are several frameworks available for PHP as well. CI is only one of about 40. They include the Zend framework, Cake, Trax, and others. There's a handy chart at that compares ten of the most popular.

If you look at them, you'll notice that postings on their user forums get very heated about which framework is the best. The truth seems to be that each has its strengths, and none is without its own weaknesses. My touchstone is that I'm busy; so frameworks should save me time, and having found one that works for me, I am sticking to it. That's why this book is just about CI.


And Who is That Man?

CI was written by Rick Ellis, rock musician turned programmer. Rick makes his living as CEO of pMachine, which sells an excellent content management system called Expression Engine. In January 2006, he wrote on his blog, :

"… I spent a couple weeks researching and installing PHP frameworks, really banging on quite a few of them, and I was absolutely dismayed. I discovered that most frameworks suffer from these problems:

  • They have horrid, terrible documentation, if it exists at all.

  • They make an endless number of assumptions regarding your knowledge and skill level, and generally expect you to figure it all out.

  • They are written for people who have root server privileges and can change system settings.

  • They assume that you have access to the command line. In fact, many do not work if you can't bash out commands.

  • They tend to require lots of dependencies, like the PEAR libraries or various open source ones.

  • They tend to be needlessly complex to use, with obtuse syntax, XML based templates, and other features that are simply not necessary for most web applications.

  • They are either ponderously big, or too minimalist to be useful.

  • The most current frameworks only run on PHP 5, which at present only has a 5% adoption rate.

I have yet to find a single PHP framework that is truly, really, actually simple to use, is thoroughly documented from top to bottom, natively includes all the tools needed to build robust applications, has a browser-based interface, and is designed for your average PHP coder, without admin privileges, who uses a standard hosting account. Not one. Which leads me to think there's a market for just such a product. …"

The result was CI, written as a spare time project. Rick generously decided to make it available, free of charge. In between running his business, he also updates CI from time to time. He's also created an excellent forum, where CI users can raise issues and share tips, as well as finding (and sometimes solving) bugs in his code. All this is available on the CI website at

Did he meet his own objectives? Read on and judge for yourself…


The 'Open Source' Business Model

There can be something disconcerting about this sort of software. If you like your software with expensive support contracts and a 'big company' name, then CI is not for you. (But then, what are you doing using PHP, anyway? PHP users know that support, and the development of PHP software, depends partly on the unpaid efforts of the 'community'—hundreds or thousands of users.)

There are some problems with community support. Consistency and high quality are not 'guaranteed'—anyone can post to the forum, and sometimes these postings are just plain wrong. (Note that if you read the small print on the licence for expensive commercial software, quality isn't guaranteed there either.) But with 'open source' products, you do have to take an intelligent interest rather than accepting everything you read on forums at face value. CI is a framework for people who are able to take an intelligent interest.

However, any sensible developer has to wonder if it's wise to invest time and energy in a product that is a 'one man band'. Rick Ellis wrote it as a spare time project, with some help from his pMachine colleague Paul Burdick. It's free. He makes no commitment to maintain it or develop it. He might go back to being a rock musician.

On the other hand, once you've downloaded it, the version you downloaded will continue to work. You don't have to rely on upgrades and patches. Rick's coding is excellent and there have been few serious bugs in it. If it works for you, then there is no reason why it shouldn't continue to work. So far I've only found two cases in which my code failed to work, and the fault was a bug in the framework rather than in my own coding on top of it. (Both bugs have since been solved.)

The CI website is the gateway to the community and forums.


What CI Doesn't Do

There are some things that CI doesn't do. Rick intended CI to be a small and 'lightweight' framework. (The zipped download for version 1.5 is only 737 KB and downloads in seconds. The Zend framework is 10 megabytes.) It's not the answer to all the problems you will ever have. But it does:

  • Make it easier and quicker to programme in PHP

  • Structure your site and help you through the architectural decisions.

One result of being 'lightweight' is that it does not have as many features as some of its rivals. Rails has achieved prominence partly because it contains 'scaffolding' and 'generators'. These are tools that automatically write certain basic scripts for you. So, for example, once you have set up a database, Rails creates 'out-of-the-box' web pages to do basic Create, Read, Update, and Delete (CRUD) operations on the database tables.

In addition, Rails allows you to write 'generators'—pieces of code that automatically write other basic scripts. The Rails community has created quite a lot of these; so you can automatically generate scripts that do all sorts of clever things.

CI doesn't do this. (There is rudimentary 'scaffolding'—scaffolds are templates that describe how the application database maybe used—in CI, but as the online manual puts it: "Scaffolding is intended for development use only. It provides very little security…. If you use scaffolding make sure you disable it immediately after you are through using it. DO NOT leave it enabled on a live site." Enough said.)

Instead CI concentrates on making basic things easy. Some of the things it handles are:

  • Session management and cookies (see Chapter 6)

  • Database access and queries (see Chapter 4)

  • Building HTML stuff, like pages and forms, and validating form entries (see Chapter 5)

  • Testing (Chapter 8)

  • Communicating on the Internet, using FTP or XMLRPC (Chapter 9)

Sound familiar? All of these are basic processes, which you will have to go through if you're building a dynamic website. CI makes these processes easier, and makes your code more likely to work.



If you are building a commercial application, the license terms for any software you are using become critical. (If you are raising venture capital, expect the VC's lawyers to go over them in detail.) No problems with CI. It has a very generous licence that is downloaded with your files.

Unlike some commercial software I could think of, CI's license even fits on one screen. Here it is, in the following screenshot:



If you already know some PHP and are writing intelligent websites, the CodeIgniter framework is all about making your life easier. It helps you

  • Save time

  • Make your site more robust

  • Achieve more sophisticated coding

It makes coding fun again, rather than a chore.

There are quite a few frameworks, and not just for the PHP language. All of them offer you chunks of pre-written code that make the repetitive or complex processes of coding easier, and impose a helpful structure on your site development.

This book does not make any comparisons between frameworks. I've found CI works for me, and I want to explain how and why. I hope that's useful to you, and that you will be able to save as much time as I did, and enjoy the coding process more, as a result.

This book takes you through some of the framework's main features, and tries to explain some of what goes on 'under the hood'.

I've used a real-world example for the code illustrations in this book to try to show that CI is a serious tool that can be quickly and easily used in a demanding environment.


About the Author

  • David Upton

    David Upton is a director of a specialized management consultancy company, based in London but working around the world. His clients include some of the world’s largest companies. He is increasingly interested in web-enabling his work, and seeking to turn ideas into robust professional applications by the simplest and easiest route. He has so far written applications for two major companies in the UK. His other interests include simulation, on which he writes a weblog which takes up far too much of his time, and thinking.

    Browse publications by this author

Latest Reviews

(1 reviews total)
Muito bom.
Book Title
Unlock this full book with a FREE 10-day trial
Start Free Trial