CodeIgniter 2 Cookbook

By Rob Foster
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Free Chapter
    CodeIgniter Basics
About this book

As a developer, there are going to be times when you’ll need a quick and easy solution to a coding problem. CodeIgniter is a powerful open source PHP framework which allows you to build simple yet powerful full-feature web applications.

CodeIgniter 2 Cookbook will give you quick access to practical recipes and useful code snippets which you can add directly into your CodeIgniter application to get the job done. It contains over 80 ready-to-use recipes that you can quickly refer to within your CodeIgniter application or project.

This book is your complete guide to creating fully functioning PHP web applications, full of easy-to-follow recipes that will aid you in any aspect of developing with CodeIgniter. CodeIgniter 2 Cookbook takes you from the basics of CodeIgniter, through e-commerce features for your applications, and ends by helping you ensure that your environment is secure for your users and SEO friendly to draw in customers.

Starting with installation and setup, CodeIgniter 2 Cookbook provides quick solutions to programming problems that you can directly include in your own projects. You will be moving through databases, EU Cookie Law, caching, and everything else in-between with useful, ready-to-go recipes. You will look at image manipulation using the Image Manipulation library, user management (building a simple CRUD interface), switching languages on the fly according to the user preference, caching content to reduce server load, and much more.

Publication date:
December 2013


Chapter 1. CodeIgniter Basics

In this chapter, we will cover:

  • Downloading and installing CodeIgniter

  • Basic configuration options

  • Managing CodeIgniter on different environments

  • Managing database settings in different environments

  • Securing system files

  • Removing index.php from the address bar using .htaccess

  • Installing and using Sparks



CodeIgniter is an easy to use, easy to set up PHP-based framework which you can use to build pretty much any web-based application you can think of. There is a little bit of configuration needed before we can start to use CodeIgniter; however, this chapter will walk you through downloading, installing, and understanding the basic configuration of CodeIgniter to help you quickly get up and running.


Downloading and installing CodeIgniter

First things first, you will need a copy of CodeIgniter to be getting on with. There are several choices: you can download a nightly build, an older version, or the current stable release. However, it's recommended that you go for the latest stable version.

How to do it...

You can get your hands on the latest stable version of CodeIgniter through the following link:

CodeIgniter will be offered as a compressed archive file. Once CodeIgniter has been downloaded, copy the package to your web folder, and unpack it as you would normally unpack an archive on your system. Once you've done this, you'll need to set some configuration options, which we'll look at next.


Basic configuration options

Configuring CodeIgniter is a lot easier than many other web frameworks available and does not require you to resort to using the command line. All you need to quickly get up and running is access to several files in the application/config/ folder. These are a few of the suggested settings which will get your CodeIgniter installation ready without too much fuss.

How to do it...

Open the file in your localhost of development environment: /path/to/codeigniter/application/config/config.php and find the following lines:


The value should be the full web address (the address that is written in your browser address bar) to the CodeIgniter installation. So if you are working in your localhost, the value should be: http://localhost/path/to/codeigniter/.


Remember to begin with a http:// and always put the trailing / slash.

If you've amended your host's file to use a domain name rather than localhost, then be sure to replace localhost with that domain name:


If you wish to use either the Session or Encryption classes in your application, the encryption key must be set. The encryption key is simply a string of characters used by CodeIgniter to encrypt various types of communication:


The preceding code line specifies whether cross-site script filtering should be applied to the Get, Post, or Cookie variables. For the sake of security, this should be set to TRUE, especially in a live environment:


The preceding code line specifies whether a cookie token is set, which if TRUE will be checked every time a form is submitted from the client side. In a live environment, it should be set to TRUE:


The preceding code line specifies whether you want to write to logs, and if so, the type of information you wish to write to those logs. For example:

  • 0: No errors are written to logs as logging is deactivated

  • 1: Error messages only (this will include PHP errors also)

  • 2: Debugging messages only

  • 3: Informational messages only

  • 4: All types of messages

The following code line is the path to the folder in which you wish to save log files:

$config["log_path"] = "/path/to/log/file"

How it works...

CodeIgniter will now respond and function according to the settings provided.

Managing CodeIgniter on different environments

In some cases, it may be useful to adapt your configuration files so that they can function on several servers or environments without having to edit or maintain each time they are moved. For example, the configuration settings you may have on your localhost are very likely to be different than those on a live or production server. Setting the configuration files correctly will save you a lot of time rather than manually switching between the two.

How to do it...

Open the /path/to/codeigniter/application/config/config.php file and replace the $config["base_url"] line with the following:

switch($_SERVER["SERVER_NAME"]) {
    case "localhost":
        $config["base_url"] = "http://localhost/path/to/codeigniter/";
    case "":
        $config["base_url"] = "";

How it works...

This is simply a case/switch statement with a SERVER_NAME check. The base_url value is set according to the server that the CodeIgniter application or project is running on.

Managing database settings on different environments

If you plan to use a database for your CodeIgniter application, then you'll need to maintain the correct connection settings. CodeIgniter keeps these settings in the database.php config file.

How to do it...

  1. Open the /path/to/codeigniter/application/config/database.php file. Chances are that the only values that need to change are the standard hostname, username, password of your database server, and the database name.

  2. Find the line that defines $active_group, which specifies the specific database settings to use for a particular hosting environment. You can switch between settings by a case/switch test similar to that used previously, for example, the following code tests for a particular server and loads the appropriate settings:

    switch($_SERVER["SERVER_NAME"]) {
        case "localhost":
            $active_group = "testing";
        case "":
            $active_group = "default"
    $db["default"]["hostname"] = "localhost";
    $db["default"]["username"] = "root";
    $db["default"]["password"] = "";
    $db["default"]["database"] = "database_name";
    $db["default"]["dbdriver"] = "mysql";
    $db["default"]["dbprefix"] = "";
    $db["default"]["pconnect"] = TRUE;
    $db["default"]["db_debug"] = FALSE;
    $db["default"]["cache_on"] = FALSE;
    $db["default"]["cachedir"] = "";
    $db["default"]["char_set"] = "utf8";
    $db["default"]["dbcollat"] = "utf8_general_ci";
    $db["default"]["swap_pre"] = "";
    $db["default"]["autoinit"] = TRUE;
    $db["default"]["stricton"] = FALSE;
    $db["testing"]["hostname"] = "localhost";
    $db["testing"]["username"] = "root";
    $db["testing"]["password"] = "";
    $db["testing"]["database"] = "database_name";
    $db["testing"]["dbdriver"] = "mysql";
    $db["testing"]["dbprefix"] = "";
    $db["testing"]["pconnect"] = TRUE;
    $db["testing"]["db_debug"] = TRUE;
    $db["testing"]["cache_on"] = FALSE;
    $db["testing"]["cachedir"] = "";
    $db["testing"]["char_set"] = "utf8";
    $db["testing"]["dbcollat"] = "utf8_general_ci";
    $db["testing"]["swap_pre"] = "";
    $db["testing"]["autoinit"] = TRUE;
    $db["testing"]["stricton"] = FALSE;
    $active_record – Specifies if you require active record support.  By default it is set to TRUE.

How it works...

All we're doing is defining the environment that the site is running on. In the preceding example, we specify two environments: either default or testing, and apply specific settings for them. So, let's look at some variable definitions.

Common values

The standard database access options are shown in the following table:

Option name

Valid options



Usually localhost

This is the server that the database sits on



The database access username



The password for the database



The name of the database

Other values

The following table shows the options that normally remain unchanged from the default setting but are here just incase you wish to change them:

Option name

Valid options




This is the type of DBMS you're using—the recipes in this book use MySQL. The value must be all lowercase.


Default: mysql, but may also be postgre, odbc, and so on

Sometimes you may wish to add a prefix to a database table name, for example, a blogging application might prefix its tables with the word "blog" so the posts table would become blog_posts.



Specifies whether you wish to maintain a persistent connection to the database.



Specifies whether you wish to display database errors on the screen. It is blank by default, but for security purposes should be set to FALSE on a live environment and TRUE while in development.



Specifies whether you want database query caching enabled.



Specifies the absolute file path to your database query cache.



Specifies the character set that CodeIgniter will use with the database.



Specifies the character collation that CodeIgniter will use with the database.



Default MySQL port. This option is not included by default, and if you wish to use a specific port for your database connection, you'll need to manually write in this line and set the value.

We will look at accessing data from a database in more detail in Chapter 6, Working with Databases.

Securing the system files

On live environments, it is strongly recommended that you move your system folder out of the web root to prevent malicious access.

How to do it...

  1. Move the system folder either by the command line or using your computer's GUI to a folder outside the publicly accessible web folder. The method to do this will be different depending on which system you are using, but I'm sure you know how to move a folder, so we will not discuss that here.

  2. After you have moved the system folder, you will need to update the $system_path variable in the path/to/codeigniter/index.php file. Look for and find the following line:

    $system_path = "path/to/system/folder";

    Amend the line to reflect the new location of the system folder. So if, for example, you moved the system folder up one level out of the web root, you should write the following line:

    $system_path = "../system";

How it works...

By moving the system folder out of the web root, you are protecting it against access via the Internet (as much as possible). The system folder is much more unlikely to be accessed in a location outside of the web root than inside.

Removing index.php from the address bar using .htaccess

It is possible to remove the index.php file from the web browser address bar when CodeIgniter is running.

How to do it...

Create or open a .htaccess file. If a .htaccess file does not already exist, you can create one as follows:


  1. Open a terminal window and type: touch/path/to/CodeIgniter/.htaccess.


  1. Create a text file in your CodeIgniter root, naming it file.htaccess.

  2. Press Windows + R to open the run dialogue.

  3. Enter the following command and click on OK:

    ren "C:\path\to\CodeIgniter\file.htaccess" .htaccess
  4. Once your .htaccess file is opened, write the following lines at the top of the file:

    <IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond $1 !^(index\.php|images|robots\.txt)
    RewriteRule ^(.*)$ index.php/$1 [L]

How it works...

This rule in the .htaccess file will remove the index.php file from the browser's address bar. CodeIgniter's index.php file is still called but it is not shown to the user in the address bar of the browser.

Installing and using Sparks

It has been the case for a long time now that to find and use extensions, libraries, and other useful snippets of code for CodeIgniter, you have to search the Internet and download code from various places such as blogs, code repositories, and so on. Useful installations for CodeIgniter were spread across the Internet and as such, may have been hard to locate. Sparks acts as a single point of reference for extensions for CodeIgniter. It's simple to install and use, and contains thousands of useful add-ons for CodeIgniter.

How to do it...

If you are using a MAC or Linux, then the command line interface is open to you.

  1. Using the terminal application on your system, navigate to the root of your CodeIgniter application and enter the following line:

    php -r "$(curl -fsSL"

    If your installation was successful, you should see something similar to:

    user@server:/path/to/codeigniter$ php -r "$(curl -fsSL"
    Pulling down spark manager from ...
    Pulling down Loader class core extension from ...
    Extracting zip package ...
    Cleaning up ...
    Spark Manager has been installed successfully!
    Try: `php tools/spark help`

    If you are using Windows, then you will need to download Sparks and unpack it manually. To do that, perform the following instructions or check out the instructions on the GetSparks website for the latest version:

  2. Create a folder named tools in the top level (root) of your CodeIgniter directory.

  3. Visit the following URL:

  4. Go to the Normal Installation section and download the Sparks package.

  5. Unpack the download into the tools folder you created in step 1.

  6. Download the Loader class extension from:

  7. Rename the MY_Loader.php.txt file to MY_Loader.php and move it to the application/core/MY_Loader.php directory in your CodeIgniter instance.

  8. Now that Sparks is installed in your CodeIgniter instance, you can begin to install extensions and packages.

    To install a package from Sparks, type the following in the command line:

    php tools/spark install [Package Version] Spark Name

    Here, Package Version is the specific version of the Spark you wish to install. You are not required to state the version, and by leaving it out, Sparks will download the latest version by default. Spark Name is the name of the Spark you wish to install, so for example, to install the example-spark (Version 1.0.0) that comes with the default installation, type in the command line:

    php tools/spark install -v1.0.0 example-spark

    If the installation was successful, you should see something similar to:

    user@server:/path/to/codeigniter$ php tools/spark install -v1.0.0 example-spark 
    [ SPARK ] Retrieving spark detail from
    [ SPARK ] From Downtown! Retrieving spark from Mercurial repository at https://url/of/the/spark/repo
    [ SPARK ] Spark installed to ./sparks/example-spark/1.0.0 - You're on fire!

How it works...

You should now be ready to begin making use of your Spark. Be sure to read the Readme file or documentation that is included with your Spark for its correct usage.

About the Author
  • Rob Foster

    Rob Foster has been working in the field of web development for almost 10 years, working for various IT sectors. He has interests in CodeIgniter, Laravel, and iOS programming.

    While not hunched over a computer ruining his eyesight, he enjoys drinking good quality wine, appreciates varieties of fine cheese, and has a liking for a pair of comfortable, elastic slacks!

    Rob has also written CodeIgniter 2 Cookbook, Packt Publishing, and was a technical editor for SUSE Linux 10 Bible, Wiley.

    Browse publications by this author
CodeIgniter 2 Cookbook
Unlock this book and the full library FREE for 7 days
Start now