Book Image

CodeIgniter 1.7

Book Image

CodeIgniter 1.7

Overview of 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. 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.
Table of Contents (21 chapters)
CodeIgniter 1.7
Credits
About the Authors
About the Reviewer
Preface

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('[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 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.