Introduction

This article explains the process I go through to setup the CodeIgniter framework and how to configure it so that I can start developing an application.

What is CodeIgniter?

If you don’t already know, CodeIgniter is an MVC framework built on PHP.  There are many features and built in functions that make building a web application fairly easy.  You can download the current version, 1.7.1, from CodeIgniter.com.  Also, check out the very well documented User Guide.

If you are interested in using the Zend library of tools with CodeIgniter, please check out How to use Zend_Search_Lucene with CodeIgniter.

Step-By-Step

For this tutorial, I’m using a WAMP Server running on my local Windows computer.  You could just as easily perform these same actions on a web server running PHP, although the paths may be different depending on if you are using Windows or a Linux based server.

Step 1

Download the latest version of CodeIgniter (1.7.1).

Before extracting the files to your server, let’s talk about where to put the files.  For security purposes, it is recommended to place the CodeIgniter files outside the path of your web server so those files cannot be accessed by typing in a URL.  So, if I access my web server by typing in http://localhost and the web server loads the website at C:\wamp\www\, then I want to place the System folder of CodeIgniter inside the C:\wamp\ folder.  Go ahead and extract the System folder from the download package to the C:\wamp\ folder.  You can place the System folder in the C:\wamp\www\ folder if you desire.  Just make sure to adjust the path name later on.

Step 2

Next, I have decided that I may want to use CodeIgniter for several applications that I develop.  To save on hosting space, I can setup all CodeIgniter applications to use the same core framework.  First, we need to move some files around from their default locations.

Open the C:\wamp\system\application\ folder.  You should see several folders listed here.  The default CodeIgniter application is setup for a single application.  We will be changing it to run multiple applications.  Create a new folder called baseApplication_1234 or something unique.  Make a copy of the index.html file and paste it inside baseApplication_1234.  Next, move all of the folders located at C:\wamp\system\application\ into C:\wamp\system\application\baseApplication_1234\.

We will configure this base application with all of our default settings that we want to use for all CodeIgniter applications.  Then, when you want to make a new application, you can simply copy the baseApplication_1234 and rename it.

Step 3

Next, we will configure the CodeIgniter application files.

Browse to C:\wamp\system\application\baseApplication_1234\config\ and open the following:

autoload.php

Modify line 42 to show:

$autoload['libraries'] = array('database', 'session');

 config.php

Modify line 14 to show (change localhost to your domain name):

$config['base_url'] = "http://localhost/";

Modify line 26 to show:

$config['index_page'] = "index.php?";

This line will be very important for the way our URLs are displayed later on.

Modify line 44 to show:

$config['uri_protocol'] = "QUERY_STRING";

Modify line 57 to show (this is optional if you want a .html to be shown on the end of your URLs):

$config['url_suffix'] = ".html";

Modify line 220 to show (add your own unique value within the quotes):

$config['encryption_key'] = "12345";

Modify lines 234 – 241 to show:

$config['sess_cookie_name']  = 'ci_session';
$config['sess_expiration']  = 7200;
$config['sess_encrypt_cookie'] = TRUE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name']  = 'ci_sessions';
$config['sess_match_ip']  = TRUE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update']  = 300;

This will require that we have a database and a table within called ci_sessions.  This table will need to have certain fields that CodeIgniter will be attempting to write session data to for each users who visits your site.  I’ll explain more later on.

database.php

Modify lines 41 – 45 to show:

$db['default']['username'] = "dbuser";
$db['default']['password'] = "mypassword";
$db['default']['database'] = "mydbname";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "dev_";

You will need to enter your correct username, password, database name, and prefix if you wish to use one.  If you use a prefix, you will need to have a table called dev_ci_session instead of ci_session.

routes.php

For the base application, the routes.php file is probably OK.  There are two lines that need to be modified when you build an application. 

$route['default_controller'] = "welcome";
$route['scaffolding_trigger'] = "12345";

Again, use some unique value for the scaffolding_trigger.  If you use a value that is hackable or nothing at all, your application will have a possible security hole.  The default controller name can be changed here as well.

Step 4

There are two helper files that I add to my projects that help translate the URLs the way I like them (http://localhost/controller/action/id.html).

MY_form_helper.php


<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('form_open'))
{
    function form_open($action = '', $attributes = '', $hidden = array())
    {
        $CI =& get_instance();

        if ($attributes == '')
        {
            $attributes = 'method="post"';
        }

        //Modify ->site_url to ->item('base_url').$action
        $action = ( strpos($action, '://') === FALSE) ? $CI->config->item('base_url').$action : $action;

        $form = '<form action="'.$action.'"';
 
        $form .= _attributes_to_string($attributes, TRUE);
 
        $form .= '>';

        if (is_array($hidden) AND count($hidden) > 0)
        {
            $form .= form_hidden($hidden);
        }

        return $form;
    }
}
?>

MY_url_helper.php


<?php
function redirect($uri = '', $method = 'location', $http_response_code = 302)
{
    $CI =& get_instance();

    switch($method)
    {
        case 'refresh' : header("Refresh:0;url=".site_url($uri));
        break;
        default   : header("Location: ".$CI->config->item('base_url').$uri, TRUE, $http_response_code);
        break;
    }
    exit;
}
?>

Create these files and save them to C:\wamp\system\application\baseApplication_1234\helpers\.  These functions will override the original CodeIgniter functions and fix some URL rewriting issues.

Step 5

Enabling URL rewriting may depend if your server supports it.  Apache has a rewrite_module that must be enabled before this will work.  Most hosting providers should already have enabled URL rewriting.

Create a new text file called .htaccess and paste the following code into it:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?$1 [L]

This will redirect all requests on your domain back to the index.php file, unless the actual path does happen to exist, then the server will serve up whatever file/directory is at that location.

Notice the ? behind index.php.  The web server is rewriting the pretty URL into a QUERY_STRING that CodeIgniter is expecting and passes in the controller and action as variables such as index.php?var1=this&var2=that. 

The .htaccess file should be stored in the C:\wamp\www\ folder or the root of your web site.

Step 6

Next, the database will need to be created and the ci_sessions table created to store the user sessions to.

After you create the MySQL database, run the following SQL and it will create the table for you:

CREATE TABLE `dev_ci_sessions` (
  `session_id` varchar(32) NOT NULL,
  `ip_address` varchar(15) NOT NULL,
  `user_agent` text NOT NULL,
  `last_activity` datetime NOT NULL,
  PRIMARY KEY  (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Make sure to remove the “dev_” if you did not setup a dbprefix.

Step 7

Next, for testing purposes, we’ll setup the baseApplication_1234 web application and attempt to run it.

Find the index.php file that came with the CodeIgniter 1.7.1 download.  It should be located in the same folder as the system folder and user_guide folder.  Copy this file into your web site root at C:\wamp\www\.

Modify line 26 as shown:

$system_folder = "c:/wamp/system";

Modify line 43 as shown:

$application_folder = "application/baseApplication_1234";

This is the line that specifies which application to load.

This index.php file is the main entry point for the application.  It will use these modifications to find the C:\wamp\system\ folder and run the correct web application.  The only other files that need to be in the C:\wamp\www\ folder are files that HTML needs to be able to access via URLs such as images and JavaScript.

Conclusion

That should be everything.  You can now try to open your web application by going to the URL, http://localhost.  The default controller is Welcome and the default action is Index, so you can also test http://localhost/welcome/index.html to verify URL rewriting works.  Remember the “.html” can be used to hide that PHP is running your web site.  In reality, index is an action of the welcome controller and doesn’t need the “.html” to be there at all.

If you run into problems, you can add this line to an action or the controller’s constructor for further information:

$this->output->enable_profiler(TRUE);

Be sure to shut this down when not needed, or it could give your users information you may not wish them to have.