Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
CodeIgniter 1.7
CodeIgniter 1.7

CodeIgniter 1.7: Improve your PHP coding productivity with the free compact open-source MVC CodeIgniter framework!

eBook
$23.39 $25.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

CodeIgniter 1.7

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 easy to use.

If you need to produce results, have better and more maintainable code, and you enjoy programming, then you should try using CodeIgniter (CI to its friends). CI is free, lightweight, and simple to install, and it really makes your life much easier. Just read this chapter to find out how:

  • What CI can do for you?

  • What is CI? What are Frameworks?

  • Comparing CI to other open source solutions.

  • What CI doesn't do?

What can CodeIgniter do for you?

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

That's quite a big claim. You have already spent some time learning PHP, HTML, CSS, a database, and so on. You need basic, not necessarily expert knowledge of PHP to benefit from CI.

CI is not for you if:

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

  • You like to write all of your code. There are people who prefer to write their code instead of using already built solutions. If you are that kind of a person, you should try CI. It is very well commented and, if you are short of time, it will help you. You won't need to reinvent the wheel again and again. CI comes with a lot of helpers, libraries, and much more for the most common tasks. Give it a try!

  • You don't like PHP; but how is that possible? With a huge community and hordes of code and tools, PHP is one of the favorite languages of the Web.

  • And definitely CI is not for you if you don't like to finish your projects on time, in a well-structured fashion, and without having to redo the same things again and again.

If you don't belong to any of the categories mentioned in the previous points, keep reading!

Save time

CI doesn't take long to learn, and it quickly pays for your effort in the time saved later. 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.

Let's take two examples, (they are explained later in this book, so don't worry now about how they work!). If you are writing a database query, this is how you might write a function within your PHP program 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:

$this->load->database('websites');
$query = $this->db->get('sites');
foreach ($query->result() as $row)
{
print $row->url;
}

Compare the character count—244 for the traditional syntax and 112 for CI. Another thing that you have to take into account when using Active Record is that you can change your database from MySQL to Postgres (or any other that is supported by CI) and you won't need to change your queries—a very helpful thing.

Now let's take an example where 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="url">
<option value="this">www.this.com</option>
<option value="that">www.that.com</option>
<option value="theother" selected>www.theother.com</option>
</select>

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

$urlarray = array(
'this' => 'www.this.com',
'that' => 'www.that.com',
'theother' => 'www.theother.com',
);
$variable = form_dropdown('url', $urlarray, 'this');

In HTML, you need to type 154 characters, and 128 in CI. Note how easily we can define the "selected" element of the drop-down menu, putting it in the third parameter. This thing alone will save us a lot of time.

Make your site more robust

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

Keep your links up-to-date automatically

Suppose you've just written a menu page, with lot of hyperlinks to other pages in your site. They are all in the traditional HTML format as shown:

<a href="http://www.mysite.com/index.php/start/hello/fred
">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 rewriting it, 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 are updated automatically.

Preventing database SQL injection attacks and form prepping

Data entry is fraught with problems. There are certain limitations of HTML and databases, as a result of which data containing symbols such as apostrophes and quotation marks may not be saved correctly, or even worse, your database may be open to malicious attacks.

For example, take this query:

SELECT id, name FROM users WHERE user = '{$user}' AND password = '{$password}';

Consider that the variables have the following values:

$user = "Fred";
$password = "1234";

Now our query would translate to:

SELECT id, name FROM users WHERE user = 'Fred' AND password = '1234';

This query will return a good result, but, what if our variables were:

$user = "Fred";
$password = "1234' OR '1' = '1";

Now our query would produce:

SELECT id, name FROM users WHERE user = 'Fred' AND password = '1234' OR '1' = '1';

This time the variable's data contains a new "where" clause with a condition that is always true. The user inserts some characters, such as " ' " to make our query behave in a way we don't want, and give bad results. It's easy to see that with this kind of attacks more than just giving bad results can be achieved, dropping tables being one of the worse things. These problems don't always come in the shape of SQL injection attacks; most of the time not prepping data correctly would bring problems too, for example:

$user = "Fred";
$password = "12xWgBq'wS";

Our password variable contains a password that looks quite secure, but will produce a problem in our query:

SELECT id, name FROM users WHERE user = 'Fred' AND password = '12xWgBq'wS';

The data will cut the query, producing some errors when executed. What can we do to prevent these problems? Well the answer to this is to prepare or "prep" our data in our 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('user', 'Fred');

You're also getting the hidden benefit of:

function form_prep($str = '')
{
// if the field name is an array we do this recursively
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = form_prep($val);
}
return $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 the code that handles special characters such as "&" 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 regexes. Some people like lying on a bed of nails, some like listening to ABBA; it's a free country. If you don't like these things, you can let CI do them for you (the regexes, not ABBA), and you needn't even be aware of the code that's working in the background for you, every time you write that one simple line of code:

echo form_input('user', 'Fred');

Besides this, CI's Active Record class automatically escapes special characters in database queries; this can also be achieved with query bindings, to give some extra automatic protection to your site; without our doing anything CI is helping us to make our site more secure.

Protect your site from XSS attacks

As stated on Wikipedia (http://en.wikipedia.org/wiki/Cross-site_scripting), XSS (cross site scripting) is a kind of vulnerability that allows some unwanted code to be executed in our application, phising attacks, data theft, and more. In order to avoid this you should validate your data.

CodeIgniter helps you to do so, in all your applications if you set global XSS filter to true in your configuration file, or whenever you need it:

$data = $this->input->xss_clean($data);

You can even use it to check potential XSS attacks within image files:

$this->input->xss_clean($file, TRUE);

The second parameter tells CI that it is an image that needs validation.

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 PHP Extension and Application Repository (PEAR) and other sources. They 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 by its user community. It puts much more sophistication in your hands.

Let's take a 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('your@your-site.com', '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 that long URLs don't get wrapped and broken up). For example, when sending attachments, the standard PHP functions can get quite complex. As a result many code writers are tempted to avoid using these functions if possible.

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

$this->email->attach('path/to/photo1.jpg');

CI does the rest, working behind the scenes. There is a function that sorts out MIME types for nearly a hundred type of attachments. 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 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 something you might have never done, and you wouldn't know how to go about it. On the other hand, CI has a nice facility that allows you to produce ZIP 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:/my_backup.zip');

Run this snippet, and you will find a ZIP archive on your C: drive containing one file. Your ZIP file 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.

What can CodeIgniter do for you?


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

That's quite a big claim. You have already spent some time learning PHP, HTML, CSS, a database, and so on. You need basic, not necessarily expert knowledge of PHP to benefit from CI.

CI is not for you if:

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

  • You like to write all of your code. There are people who prefer to write their code instead of using already built solutions. If you are that kind of a person, you should try CI. It is very well commented and, if you are short of time, it will help you. You won't need to reinvent the wheel again and again. CI comes with a lot of helpers, libraries, and much more for the most common tasks. Give it a try!

  • You don't like PHP; but how is that possible? With a huge community and hordes of code and tools, PHP is one of the favorite languages of the Web.

  • And definitely CI is not for you if you don't like to finish your projects on time, in a well-structured fashion, and without having to redo the same things again and again.

If you don't belong to any of the categories mentioned in the previous points, keep reading!

Save time

CI doesn't take long to learn, and it quickly pays for your effort in the time saved later. 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.

Let's take two examples, (they are explained later in this book, so don't worry now about how they work!). If you are writing a database query, this is how you might write a function within your PHP program 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:

$this->load->database('websites');
$query = $this->db->get('sites');
foreach ($query->result() as $row)
{
print $row->url;
}

Compare the character count—244 for the traditional syntax and 112 for CI. Another thing that you have to take into account when using Active Record is that you can change your database from MySQL to Postgres (or any other that is supported by CI) and you won't need to change your queries—a very helpful thing.

Now let's take an example where 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="url">
<option value="this">www.this.com</option>
<option value="that">www.that.com</option>
<option value="theother" selected>www.theother.com</option>
</select>

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

$urlarray = array(
'this' => 'www.this.com',
'that' => 'www.that.com',
'theother' => 'www.theother.com',
);
$variable = form_dropdown('url', $urlarray, 'this');

In HTML, you need to type 154 characters, and 128 in CI. Note how easily we can define the "selected" element of the drop-down menu, putting it in the third parameter. This thing alone will save us a lot of time.

Make your site more robust

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

Keep your links up-to-date automatically

Suppose you've just written a menu page, with lot of hyperlinks to other pages in your site. They are all in the traditional HTML format as shown:

<a href="http://www.mysite.com/index.php/start/hello/fred
">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 rewriting it, 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 are updated automatically.

Preventing database SQL injection attacks and form prepping

Data entry is fraught with problems. There are certain limitations of HTML and databases, as a result of which data containing symbols such as apostrophes and quotation marks may not be saved correctly, or even worse, your database may be open to malicious attacks.

For example, take this query:

SELECT id, name FROM users WHERE user = '{$user}' AND password = '{$password}';

Consider that the variables have the following values:

$user = "Fred";
$password = "1234";

Now our query would translate to:

SELECT id, name FROM users WHERE user = 'Fred' AND password = '1234';

This query will return a good result, but, what if our variables were:

$user = "Fred";
$password = "1234' OR '1' = '1";

Now our query would produce:

SELECT id, name FROM users WHERE user = 'Fred' AND password = '1234' OR '1' = '1';

This time the variable's data contains a new "where" clause with a condition that is always true. The user inserts some characters, such as " ' " to make our query behave in a way we don't want, and give bad results. It's easy to see that with this kind of attacks more than just giving bad results can be achieved, dropping tables being one of the worse things. These problems don't always come in the shape of SQL injection attacks; most of the time not prepping data correctly would bring problems too, for example:

$user = "Fred";
$password = "12xWgBq'wS";

Our password variable contains a password that looks quite secure, but will produce a problem in our query:

SELECT id, name FROM users WHERE user = 'Fred' AND password = '12xWgBq'wS';

The data will cut the query, producing some errors when executed. What can we do to prevent these problems? Well the answer to this is to prepare or "prep" our data in our 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('user', 'Fred');

You're also getting the hidden benefit of:

function form_prep($str = '')
{
// if the field name is an array we do this recursively
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = form_prep($val);
}
return $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 the code that handles special characters such as "&" 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 regexes. Some people like lying on a bed of nails, some like listening to ABBA; it's a free country. If you don't like these things, you can let CI do them for you (the regexes, not ABBA), and you needn't even be aware of the code that's working in the background for you, every time you write that one simple line of code:

echo form_input('user', 'Fred');

Besides this, CI's Active Record class automatically escapes special characters in database queries; this can also be achieved with query bindings, to give some extra automatic protection to your site; without our doing anything CI is helping us to make our site more secure.

Protect your site from XSS attacks

As stated on Wikipedia (http://en.wikipedia.org/wiki/Cross-site_scripting), XSS (cross site scripting) is a kind of vulnerability that allows some unwanted code to be executed in our application, phising attacks, data theft, and more. In order to avoid this you should validate your data.

CodeIgniter helps you to do so, in all your applications if you set global XSS filter to true in your configuration file, or whenever you need it:

$data = $this->input->xss_clean($data);

You can even use it to check potential XSS attacks within image files:

$this->input->xss_clean($file, TRUE);

The second parameter tells CI that it is an image that needs validation.

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 PHP Extension and Application Repository (PEAR) and other sources. They 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 by its user community. It puts much more sophistication in your hands.

Let's take a 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('your@your-site.com', '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 that long URLs don't get wrapped and broken up). For example, when sending attachments, the standard PHP functions can get quite complex. As a result many code writers are tempted to avoid using these functions if possible.

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

$this->email->attach('path/to/photo1.jpg');

CI does the rest, working behind the scenes. There is a function that sorts out MIME types for nearly a hundred type of attachments. 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 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 something you might have never done, and you wouldn't know how to go about it. On the other hand, CI has a nice facility that allows you to produce ZIP 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:/my_backup.zip');

Run this snippet, and you will find a ZIP archive on your C: drive containing one file. Your ZIP file 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.

What CI doesn't do


There are some things that CI doesn't do. CI was intended to be a small and lightweight framework. The zipped download for version 1.7.2 is only 2.1 MB and is downloaded in seconds, whereas the Zend framework is 10 MB. It won't answer all the problems you will have. But it does:

  • Make it easy and quick to program in PHP

  • Structure your site and help you through the architectural decisions

As a result of being lightweight, it does not have as many features as some of its rivals. Other frameworks such as Rails, CakePHP, or Symfony have scaffolding and generators. These tools automatically write certain basic scripts for you.

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 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)

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

Sounds 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. Join this outstanding community; it will help you in case you need it (at the CodeIgniter forums). You can even share code at the Wiki (http://codeigniter.com/wiki/), and you will find why CI is so popular.

Yes, but…what is CodeIgniter? What are frameworks?


Shortly after programming was invented, it was noticed that it involved many repetitive operations. And maybe shortly after that, Ada Lovelace—spanner in hand adjusting Babbage's differential engine—or Alan Turing at Bletchley Park decided to modularize code. So, you only had to write certain chunks once, and could then reuse 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—lot of chunks of code stored in separate files, which simplify the coding of repetitive operations. In the previous examples, connecting to the database or building HTML form elements are abstracted and simplified for you. You call a function in the framework, which is easy to handle than the original code.

It goes beyond that. Writing code involves continuous choices between the many ways of tackling the same problem. Most frameworks 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 they are sensible choices, it makes your life much simpler. If not, it's like trying to write a sales brochure using Excel, or showing 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 these decisions for you—starting off with a sensible foundation for your program and guiding you through the next steps.

A framework will also improve team programming. As every developer has to adhere to the framework syntax and structure, it is an important part of software maintainability. The code you write today needs to be readable by other people in future. Imagine you arrive to a new workplace and then you inherit a couple of projects. In a perfect world those projects would be well commented, but reality usually hits... Wouldn't it be nice to have a central resource of documentation to get started with those projects?

Most frameworks will offer good documentation. CI isn't an exception; everything is well documented—functions, structures, conventions. You won't have to imagine what a certain function does, you will know it. A very good starting point, don't you think?

Nowadays there are lot of frameworks out there, not only PHP frameworks but Ruby frameworks, Python frameworks, and so on. For PHP programmers there are hundreds of options (well, may not be hundreds, but if we do search for PHP frameworks the results will be overwhelming). Of all these options there are some that are more popular; CI is among them, with others such as CakePHP, Zend Framework, Symfony, and more.

As you are reading this book, you are interested in PHP frameworks, especially CodeIgniter, so we will keep to it.

If you take a look at http://phpframeworks.com/ and http://www.phpframeworks.com/top-10-php-frameworks/, you will see how well CodeIgniter is doing. CI is very popular as a PHP framework; with this book you will know, why. Also if you look at some forums and blogs you'll notice that postings 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. In time you will learn to decide which framework to use in which project. It is recommended that you should think about which tool to use, before starting your projects. Choose the one that will help you to end with a well done project, in good time, and with the best possible scalability. Most of the times CI helps achieve this.

Comparing CI to other open source solutions (CakePHP and Joomla!)


For one reason or another one should compare these three most of the time and, of course, use one of them. There are other solutions out there, as we have commented before, "few" is not the word to describe PHP frameworks.

Though you would like to have Zend Framework and Symfony in your toolbox, for now, let's use these three for comparison. For example, when Jose heard about frameworks it was all about Ruby on Rails. Before that he used to write his own code for every project. Though Ruby on Rails is a very good framework, for him—a PHP programmer at heart—that was not the solution.

Searching for a PHP framework that was similar to Ruby on Rails, but PHP made, CakePHP was one option. It was quite similar in concept to Ruby on Rails, it also had the same convention-driven architecture that you need to learn before using it. It will pay-back with lots of functionality, automation, and more. But keep in mind that the learning curve is steeper than CodeIgniter's.

Using CakePHP requires you to adhere to some strict conventions (those can be changed but the out-of-the-box software comes with them). Most of the time they are naming conventions, but there are database conventions also.

After some time, because of curiosity, in spite of incredible lack of learning time (some nearby shouting boss also helped), continuing research of PHP frameworks found CodeIgniter. The most convincing thing was the documentation (CakePHP wasn't as well documented as it is today).

CI has less conventions, and minimal configuration, also you can forget about most of them and work as you have always done. You don't want to use models, and you don't have to (though it is recommended). That said, one of the strengths of CI is just that—download it and start programming.

Joomla! is not exactly a framework, it helps you build websites faster. Also in the latest versions it has turned into the MVC (Model-View-Controller) pattern. The good part of Joomla! is that it is a CMS (Content Management System), but I think it is also its bad part, as sometimes you just don't need so much as Joomla! has to offer. Of course you can develop your own solution over Joomla!, but then what's the point of using Joomla!, and not using what it has to offer?

CI, usually, is the most well-balanced of the three, but let's see how we can choose one of them.

What to choose

With all those options out there, why should you go with CI? The answer—it's not that easy and involves, in most cases, personal preference. There will be projects that will be better suited to one of the other two options. Let's see some examples that will guide us.

When to choose Joomla!

  • If we need a CMS (it may sound redundant, but...).

  • If there is already a component, module, or some other functionality that we need, then there is something built that can help us carry out the project in no time.

  • If the client asks you to use it. Joomla! is a well known software, and sometimes your client can just ask you to use it.

When to choose CakePHP

  • If there are lot of relations between database tables. Cake's Active Record capabilities are slightly more powerful than CI's.

  • If you need to build some admin zone quickly. Cake's bake script can read your database and build some CRUD (Create, Read, Update, Delete) pages for your tables.

When to choose CodeIgniter

  • If the project doesn't have or doesn't need a very rigid structure. Also CI is good for working with legacy code.

  • If you need to start programming right away, without having to learn a lot of conventions.

  • If you need some software that helps you, with the confidence that it will help you in the way you really need, and learn the way something needs to be done.

  • If you know PHP, you can use CI.

  • The client needs some solution built specifically for him/her, and not an adapted solution (that would be in case of some Joomla! components/modules).

Most of the time we will be using CI because it is very flexible. If you like programming CI will help you in doing it. It will seem as if CI isn't even there. You realize it only when you look at the time you are gaining and the better structure of your project.

If you are new to frameworks it is recommended that you get CI, maybe later you use another one (probably both of them), but CI will always have a place in your heart.

Note

Packt Publishing has books on some other frameworks and Joomla!. It is recommended to read them, it will give you a broader view of things.

For books on Joomla visit http://www.packtpub.com/joomla-version-1-5/book.

For books on CakePHP visit http://www.packtpub.com/cakephp-application-development/book.

License


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. With CI this is not a problem. It has a very generous license that is downloaded with your files.

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

Summary


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

  • Save time

  • Make your site more robust

  • Achieve more sophisticated coding

  • It makes coding fun again, rather than a chore

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

This book does not make any comparisons between frameworks. CI works for most, and we will see, how and why. It will be useful for you too, and you will be able to save much time and, as a result, enjoy the coding process more.

This book takes you through some of the framework's main features, and tries to explain some of what goes on "under the hood". We've used a real-world example for the code illustrations in this book to show that CI is a serious tool that can be quickly and easily used in a demanding environment.

Enjoy!

Left arrow icon Right arrow icon

Key benefits

  • Clear, structured tutorial on working with CodeIgniter for rapid PHP application development
  • Careful explanation of the basic concepts of CodeIgniter and its MVC architecture
  • Use CodeIgniter with databases, HTML forms, files, images, sessions, and email
  • Full of ideas and examples with instructions making it ideal for beginners to CodeIgniter

Description

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. This book will start you from the basics, installing CodeIgniter, understanding its structure and the MVC pattern. You will also learn how to use some of the most important CodeIgniter libraries and helpers, upload it to a shared server, and take care of the most common problems. If you are new to CodeIgniter, this book will guide you from bottom to top. If you are an experienced developer or already know about CodeIgniter, here you will find ideas and code examples to compare to your own.

Who is this book for?

This book is for developers who are new to CodeIgniter. Basic skills in PHP and MySQL are required, but only rudimentary object-oriented knowledge is needed. If you're looking for a better way to develop PHP applications, or want to find out more about the CodeIgniter framework as a viable option for one of your own projects, this book will help you.

What you will learn

  • Download, install, and configure a CodeIgniter site and learn how to use mod_rewrite to generate better URLs
  • Organize a dynamic web site using the Model-View-Controller (MVC) pattern
  • Simplify your database access by integrating databases such as MySQL
  • Make your site more robust and professional by using CI s built-in classes
  • Understand the structure of a CI site and its object-oriented aspects
  • Reduce the code necessary to create a form using form helper ñ one of the fine features of CodeIgniter
  • Take any library or code, from your previous work, third-party code, etc. and put it to use inside CodeIgniter
  • Generate Create, Update, Delete, and Read (C.R.U.D) entries on each database table
  • Create multi-language sites, handle files, images, sessions, and send email easily with the help of CI
  • Work with files easily ñ upload them, download them, and put them into a Zip file
  • Test your code with error handling, unit testing, benchmarking, and profiling with the help of CI
  • Build a dynamic web site quickly and easily using CodeIgniter s prepared code
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 09, 2009
Length: 300 pages
Edition : 1st
Language : English
ISBN-13 : 9781847199485
Languages :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Nov 09, 2009
Length: 300 pages
Edition : 1st
Language : English
ISBN-13 : 9781847199485
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 147.97
CodeIgniter Web Application Blueprints
$48.99
CodeIgniter 1.7
$43.99
CodeIgniter 2 Cookbook
$54.99
Total $ 147.97 Stars icon

Table of Contents

15 Chapters
Introduction to CodeIgniter Chevron down icon Chevron up icon
Setting up a CodeIgniter Site Chevron down icon Chevron up icon
Navigating Your Site Chevron down icon Chevron up icon
Using CI to Simplify Databases Chevron down icon Chevron up icon
Simplifying HTML Pages and Forms Chevron down icon Chevron up icon
Simplifying Sessions and Security Chevron down icon Chevron up icon
CodeIgniter and Objects Chevron down icon Chevron up icon
Improving Our Application with Third-Party Code Chevron down icon Chevron up icon
Using CI to Communicate Chevron down icon Chevron up icon
How CI Helps to Provide Dynamic Information Chevron down icon Chevron up icon
Using CI to Handle Files and Images Chevron down icon Chevron up icon
Moving Your Site to the WWW Chevron down icon Chevron up icon
CRUD—or Putting It All Together Chevron down icon Chevron up icon
The Verdict on CI Chevron down icon Chevron up icon
Resources and Extensions Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(7 Ratings)
5 star 42.9%
4 star 42.9%
3 star 0%
2 star 14.3%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Manuel Ambulo Mar 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good tutorial
Amazon Verified review Amazon
prolificreviewer713 Apr 04, 2010
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a great reference book not only to read while away from your computer but also to keep next to the keyboard as you are developing. I typically do not read these types of books cover to cover but being new to the whole MVC concept had me reading most of the book page by page. The MVC design principals discussed are balanced in the fact that they show you why the MVC design is better then most ad-hoc systems. The Active Record class implementation should be reason enough to use the framework on any PHP site that uses CRUD (Create, Read, Update, Delete) / databases in general.The sometimes confusing part of my title comes in to play when skimming over the book, it seems like they reference things a few pages back which means you have to backtrack to understand where the example or corresponding part is at (if you read page to page this will probably not be a problem). Overall a highly recommended framework and book!
Amazon Verified review Amazon
The Reader Jan 07, 2010
Full star icon Full star icon Full star icon Full star icon Full star icon 5
An excellent guide to the CodeIgniter framework. While the online documentation for the framework is excellent, this book reduces the learning curve considerably.
Amazon Verified review Amazon
HappyChickenLogistics Mar 20, 2010
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I bought this mainly because I found myself away from the computer often but I still wanted to learn how to use the framework when I couldn't use the computer.The writing is well done and I think this is a great resource for anyone who is somewhat new to Codeigniter, PHP, or MVC (or at least Codeigniter's version of it). While a lot of the information contained within can be easily obtained online, this book does a great job of explaining things clearly and providing nice examples and walkthroughs.If you are a more advanced user then this book might not be for you. Once you start delving into some of the more advanced portions of Codeigniter you will quickly find yourself searching for more answers online, although it is hard to fault this book for not covering everything.Overall a nice resource to have.
Amazon Verified review Amazon
Konstantin Nov 01, 2010
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I highly recommend this book. its a great resource to get you started with CI. Yes there are typos, but the knowledge you get from this book is so great, you yourself will see all the typos. I recommend it !
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
Modal Close icon
Modal Close icon