Richland College Multimedia Learning Center

Digital Media Programming with PHP and MySQL

Digital Media Programming with PHP and MySQL

Introduction to CodeIgniter

Introduction to CodeIgniter

IMPORTANT NOTE: This handout covers CodeIgniter 3. There are significant differences between CodeIgniter 2.2 and CodeIgniter 3.

From the CodeIgniter User Guide's Welcome Page:

CodeIgniter is an Application Development Framework - a toolkit - for people who build web sites using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task.

CodeIgniter is right for you if:

There is a really good summary of CodeIgniter at the CodeIgniter at a Glance page.

The CodeIgniter User Guide is fairly complete, but it is also just a bit confusing and daunting if you are just getting started. In the rest of this handout, I will attempt to summarize and clarify the world of using CodeIgniter.


MVC Frameworks

Probably one of the most confusing aspects of CodeIgniter is its use of Model-View-Controller (MVC) frameworks.

Most Web sites these days can be thought of as online applications.

MVC is a software approach that separates Web application logic from presentation.

What this really means is that your Web pages can contain mostly the display (presentation) of information, rather than a bunch of computations, database accesses, and other logic. This display of information is in a View page. A View will normally be a Web page, but in CodeIgniter, a view can also be a page fragment like a header or footer.

The computations, database access, decisions, and other logic can mostly be put into separate Model pages.

The Controller is an additional page which serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a Web page.

So, even though the accepted term is "MVC", the pages are normally used in this order:

  1. A Controller page makes some decisions about what other pages will be needed for the request.
  2. A Model page is usually given the task of getting the data and other information that the user will want to see.
  3. A View page displays the information to the user as a Web page.

CodeIgniter URLs

Another potentially confusing aspect of CodeIgniter is its use of parts of the URL to convey information to the MVC framework.

These parts of the URL, usually called segments, look like this:

	http://www.example.com/index.php/controller/function/ID

By default, index.php will be included in your CodeIgniter URLs.

Also by default, the complete URL as shown above, up to and including the controller page, must be given in the browser's address bar in order for the hypertext-link URLs and form action-attribute URLs to work in CodeIgniter. The function and ID are optional. What this usually means is that...

on the sites that I work on with CodeIgniter, I usually redirect the user from a URL that they might type in like this:

http://www.example.com/
to the full URL, like this:
http://www.example.com/index.php/home
(assuming that the default controller in this example is home.php).

Also, please note that index.php is the page in the CodeIgniter world which sets a bunch of configuration values and then kicks off the controller processing. There is a section later in this e-handout which gives details about index.php in the CodeIgniter framework.

And CodeIgniter even has some built-in "helper" classes for constructing URLs and hypertext links. One article at StackOverflow.com gives some good hints and ideas.


Controllers

Controllers are the heart of your CodeIgniter Web application, since they determine how HTTP requests should be handled.

To be more specific, a Controller page is a PHP class file that is named so it is associated with the CodeIgniter URL that is requesting a Web page.

So if you have this URL in your browser:

	http://www.example.com/index.php/Blog/

then in the above example, CodeIgniter would attempt to find a controller file named Blog.php and load it.

Controller class files are stored in your application/controllers/ folder.

When a Controller's name matches the first segment of a URL, it will be loaded.

All class filenames (libraries, drivers, controllers and models) must be named in a Ucfirst-like manner or in other words - they must start with a capital letter.


Models

You are not required by CodeIgniter to use Model pages. But you will benefit from the full advantages of the MVC framework, of course, only if you also use the M part of MVC, meaning: The Model pages.

Models are PHP classes that are designed to work with information in your database. For example, if you use CodeIgniter to manage a blog, you might have a model class that contains functions to insert, update, and retrieve your blog data in the database.

Model classes are stored in your application/models/ folder.

Below is some sample code for a model class. Class names must have the first letter capitalized with the rest of the name being lowercase. Make sure your class extends the base Model class.

class User_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }
}

then your filename will be this:

application/models/User_model.php

Your models will typically be loaded and called from within your controller functions.

Here is an example of a controller that loads a model, then displays a view (See the next section for Views.):

class Blog_controller extends CI_Controller {

    function Blog()
    {
        $this->load->model('Blog');

        $data['query'] = $this->Blog->get_last_ten_entries();

        $this->load->view('blog', $data);
    }
}

Please note these points about the above code:


Views

A view is a Web page, or a page fragment: like a header, footer, sidebar, etc. In fact, views can be embedded within other views.

Views are never called directly. They must be loaded by a controller. This situation is in keeping with the fact that in an MVC framework, the Controller acts as the traffic cop, so it is responsible for finding and displaying a particular view.

Here is a sample of a controller page which displays a view. This is page application/controllers/Blog.php:

<?php
class Blog extends CI_Controller {

	function index()
	{
		$this->load->view('blogview');
	}
}
?>
Now here is what the view page application/views/blogview.php might look like:

<html>
<head>
<title>My Blog
</head>
<body>
	<h1>Welcome to my Blog!</h1>
</body>
</html>

Please note these points about the above code:

If you ever need to send (dynamic) data into your view to display it, you usually put the data into an array or into an object and pass it as the second parameter to the load->view() call. Note carefully that if you use an object, the class variables will be turned into array elements for use by the view.

There is a good example of passing data into a view in the CodeIgniter User Guide in the section "Adding Dynamic Data to the View". You will need to scroll down a bit to find that section.


The Index Page

As I mentioned earlier in this e-handout, index.php is the page in the CodeIgniter world which sets a bunch of configuration values and then kicks off the controller processing.

Here is what a typical index.php page will look like on a CodeIgniter site:

<?php
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014 - 2015, British Columbia Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package	CodeIgniter
 * @author	EllisLab Dev Team
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
 * @copyright	Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
 * @license	http://opensource.org/licenses/MIT	MIT License
 * @link	http://codeigniter.com
 * @since	Version 1.0.0
 * @filesource
 */

/*
 *---------------------------------------------------------------
 * APPLICATION ENVIRONMENT
 *---------------------------------------------------------------
 *
 * You can load different configurations depending on your
 * current environment. Setting the environment also influences
 * things like logging and error reporting.
 *
 * This can be set to anything, but default usage is:
 *
 *     development
 *     testing
 *     production
 *
 * NOTE: If you change these, also change the error_reporting() code below
 */
	define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');

/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */
switch (ENVIRONMENT)
{
	case 'development':
		error_reporting(-1);
		ini_set('display_errors', 1);
	break;

	case 'testing':
	case 'production':
		ini_set('display_errors', 0);
		if (version_compare(PHP_VERSION, '5.3', '>='))
		{
			error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
		}
		else
		{
			error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE);
		}
	break;

	default:
		header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
		echo 'The application environment is not set correctly.';
		exit(1); // EXIT_ERROR
}

/*
 *---------------------------------------------------------------
 * SYSTEM FOLDER NAME
 *---------------------------------------------------------------
 *
 * This variable must contain the name of your "system" folder.
 * Include the path if the folder is not in the same directory
 * as this file.
 */
	$system_path = 'system';

/*
 *---------------------------------------------------------------
 * APPLICATION FOLDER NAME
 *---------------------------------------------------------------
 *
 * If you want this front controller to use a different "application"
 * folder than the default one you can set its name here. The folder
 * can also be renamed or relocated anywhere on your server. If
 * you do, use a full server path. For more info please see the user guide:
 * http://codeigniter.com/user_guide/general/managing_apps.html
 *
 * NO TRAILING SLASH!
 */
	$application_folder = 'application';

/*
 *---------------------------------------------------------------
 * VIEW FOLDER NAME
 *---------------------------------------------------------------
 *
 * If you want to move the view folder out of the application
 * folder set the path to the folder here. The folder can be renamed
 * and relocated anywhere on your server. If blank, it will default
 * to the standard location inside your application folder. If you
 * do move this, use the full server path to this folder.
 *
 * NO TRAILING SLASH!
 */
	$view_folder = '';


/*
 * --------------------------------------------------------------------
 * DEFAULT CONTROLLER
 * --------------------------------------------------------------------
 *
 * Normally you will set your default controller in the routes.php file.
 * You can, however, force a custom routing by hard-coding a
 * specific controller class/function here. For most applications, you
 * WILL NOT set your routing here, but it's an option for those
 * special instances where you might want to override the standard
 * routing in a specific front controller that shares a common CI installation.
 *
 * IMPORTANT: If you set the routing here, NO OTHER controller will be
 * callable. In essence, this preference limits your application to ONE
 * specific controller. Leave the function name blank if you need
 * to call functions dynamically via the URI.
 *
 * Un-comment the $routing array below to use this feature
 */
	// The directory name, relative to the "controllers" folder.  Leave blank
	// if your controller is not in a sub-folder within the "controllers" folder
	// $routing['directory'] = '';

	// The controller class file name.  Example:  mycontroller
	// $routing['controller'] = '';

	// The controller function you wish to be called.
	// $routing['function']	= '';


/*
 * -------------------------------------------------------------------
 *  CUSTOM CONFIG VALUES
 * -------------------------------------------------------------------
 *
 * The $assign_to_config array below will be passed dynamically to the
 * config class when initialized. This allows you to set custom config
 * items or override any default config values found in the config.php file.
 * This can be handy as it permits you to share one application between
 * multiple front controller files, with each file containing different
 * config values.
 *
 * Un-comment the $assign_to_config array below to use this feature
 */
	// $assign_to_config['name_of_config_item'] = 'value of config item';



// --------------------------------------------------------------------
// END OF USER CONFIGURABLE SETTINGS.  DO NOT EDIT BELOW THIS LINE
// --------------------------------------------------------------------

/*
 * ---------------------------------------------------------------
 *  Resolve the system path for increased reliability
 * ---------------------------------------------------------------
 */

	// Set the current directory correctly for CLI requests
	if (defined('STDIN'))
	{
		chdir(dirname(__FILE__));
	}

	if (($_temp = realpath($system_path)) !== FALSE)
	{
		$system_path = $_temp.'/';
	}
	else
	{
		// Ensure there's a trailing slash
		$system_path = rtrim($system_path, '/').'/';
	}

	// Is the system path correct?
	if ( ! is_dir($system_path))
	{
		header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
		echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: '.pathinfo(__FILE__, PATHINFO_BASENAME);
		exit(3); // EXIT_CONFIG
	}

/*
 * -------------------------------------------------------------------
 *  Now that we know the path, set the main path constants
 * -------------------------------------------------------------------
 */
	// The name of THIS file
	define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));

	// Path to the system folder
	define('BASEPATH', str_replace('\\', '/', $system_path));

	// Path to the front controller (this file)
	define('FCPATH', dirname(__FILE__).'/');

	// Name of the "system folder"
	define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));

	// The path to the "application" folder
	if (is_dir($application_folder))
	{
		if (($_temp = realpath($application_folder)) !== FALSE)
		{
			$application_folder = $_temp;
		}

		define('APPPATH', $application_folder.DIRECTORY_SEPARATOR);
	}
	else
	{
		if ( ! is_dir(BASEPATH.$application_folder.DIRECTORY_SEPARATOR))
		{
			header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
			echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF;
			exit(3); // EXIT_CONFIG
		}

		define('APPPATH', BASEPATH.$application_folder.DIRECTORY_SEPARATOR);
	}

	// The path to the "views" folder
	if ( ! is_dir($view_folder))
	{
		if ( ! empty($view_folder) && is_dir(APPPATH.$view_folder.DIRECTORY_SEPARATOR))
		{
			$view_folder = APPPATH.$view_folder;
		}
		elseif ( ! is_dir(APPPATH.'views'.DIRECTORY_SEPARATOR))
		{
			header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
			echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: '.SELF;
			exit(3); // EXIT_CONFIG
		}
		else
		{
			$view_folder = APPPATH.'views';
		}
	}

	if (($_temp = realpath($view_folder)) !== FALSE)
	{
		$view_folder = $_temp.DIRECTORY_SEPARATOR;
	}
	else
	{
		$view_folder = rtrim($view_folder, '/\\').DIRECTORY_SEPARATOR;
	}

	define('VIEWPATH', $view_folder);

/*
 * --------------------------------------------------------------------
 * LOAD THE BOOTSTRAP FILE
 * --------------------------------------------------------------------
 *
 * And away we go...
 */
require_once BASEPATH.'core/CodeIgniter.php';

Please note these items about the above index.php page:


Installation

Speaking of installation, there are several things that I want to clarify, in addition to the Installation Instructions mentioned just above.


Cool CodeIgniter Stuff

If you are wondering why you would want to go to the trouble of using an MVC framework like CodeIgniter, I am about to give you a partial answer. Here are some of the reasons that you might seriously consider using CodeIgniter for your Web site:

  1. An MVC framework forces some organization onto your site's pages. This in itself can be a sufficient reason to use CodeIgniter. But there is more...
  2. CodeIgniter includes some "helper" classes for common PHP tasks such as:
    • Managing and using arrays.
    • Creating and using CAPTCHA security images.
    • Managing and using cookies.
    • Managing and using dates.
    • Managing and using directories.
    • Managing and using e-mail.
    • Managing and using strings.
    • And more. See the sections "General: Helper Functions" and "Helpers" in the User Guide.
  3. CodeIgniter also includes some really helpful classes for common site functions such as:
    • Shopping Cart
    • E-mail
    • Encryption
    • File uploading
    • Form validation
    • FTP
    • Image manipulation, including resizing, thumbnail creation, cropping, rotating, and watermarking. This class alone justifies the use of CodeIgniter, in my opinion!
    • Pagination. This class also hugely justifies the use of CodeIgniter.
    • Zip-file encoding
    • And more. See the section "Libraries" in the User Guide.

Example

Here is a small example of how to create your own CodeIgniter site. This sample code started with a fresh installation of CodeIgniter in the codeigniter directory at one of my class Web sites, http://giraffesarecool.xyz

I made these changes to the default/fresh installation, to get this sample page to display at giraffesarecool.xyz:

  1. At the bottom of file application/config/routes.php, I changed this line:
    $route['default_controller'] = 'welcome';
    to this line ('welcome' becomes 'home'):
    $route['default_controller'] = 'home';
  2. I copied file application/controllers/Welcome.php and saved it as application/controllers/Home.php.

  3. I changed TWO THINGS in file application/controllers/Home.php:
    1. The class name is now Home, so the class declaration now looks like this:
      class Home extends CI_Controller {
    2. The line which loads the view now looks like this:
      $this->load->view('home_page');
  4. I copied file application/views/welcome_message.php and saved it as file application/views/home_page.php. I changed it a bit so it looks more or less like a "Home" page.

  5. I uploaded the new and changed pages to the proper directories under the codeigniter directory at giraffesarecool.xyz.

Here is what the view page home_page.php looks like:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Home</title>

	<style type="text/css">

	::selection { background-color: #E13300; color: white; }
	::-moz-selection { background-color: #E13300; color: white; }

	body {
		background-color: #fff;
		margin: 40px;
		font: 13px/20px normal Helvetica, Arial, sans-serif;
		color: #4F5155;
	}

	h1 {
		color: #444;
		background-color: transparent;
		border-bottom: 1px solid #D0D0D0;
		font-size: 19px;
		font-weight: normal;
		margin: 0 0 14px 0;
		padding: 14px 15px 10px 15px;
	}

	#body {
		margin: 0 15px 0 15px;
	}

	p.footer {
		text-align: right;
		font-size: 11px;
		border-top: 1px solid #D0D0D0;
		line-height: 32px;
		padding: 0 10px 0 10px;
		margin: 20px 0 0 0;
	}

	#container {
		margin: 10px;
		border: 1px solid #D0D0D0;
		box-shadow: 0 0 8px #D0D0D0;
	}
	
	#beginning {
	  margin-left: 20px;
	}
	</style>
</head>
<body>

<div id="container">
	<h1>Home</h1>

  <div id="beginning">
    <p>This is just the beginning of an adventure with CodeIgniter!</p>
  </div>
	<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo  (ENVIRONMENT === 'development') ?  'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>
</div>

</body>
</html>