CodeIgniter Documentation

CodeIgniter Documentation
3.0-dev
EllisLab, Inc.
2014 02 02
Contents
i
ii
CodeIgniter Documentation, 3.0-dev
• License Agreement
• Change Log
•
•
•
•
•
•
•
• Driver
•
• CodeIgniter
Contents
1
CodeIgniter Documentation, 3.0-dev
2
Contents
CHAPTER 1
• Welcome to CodeIgniter
3
CodeIgniter Documentation, 3.0-dev
4
Chapter 1.
CHAPTER 2
• Server Requirements
• Credits
5
CodeIgniter Documentation, 3.0-dev
6
Chapter 2.
CHAPTER 3
• Downloading CodeIgniter
• Installation Instructions
• Upgrading From a Previous Version
• Troubleshooting
7
CodeIgniter Documentation, 3.0-dev
8
Chapter 3.
CHAPTER 4
• Getting Started With CodeIgniter
• CodeIgniter at a Glance
• CodeIgniter Features
• Application Flow Chart
• Model-View-Controller
• Design and Architectural Goals
9
CodeIgniter Documentation, 3.0-dev
10
Chapter 4.
CHAPTER 5
• Tutorial
• Static pages
• News section
• Create news items
• Conclusion
11
CodeIgniter Documentation, 3.0-dev
12
Chapter 5.
CHAPTER 6
6.1 General Topics
6.1.1 CodeIgniter URLs
By default, URLs in CodeIgniter are designed to be search-engine and human friendly. Rather than using the standard
“query string” approach to URLs that is synonymous with dynamic systems, CodeIgniter uses a segment-based
approach:
example.com/news/article/my_article
: Query string URLs can be optionally enabled, as described below.
URI Segments
The segments in the URL, in following with the Model-View-Controller approach, usually represent:
example.com/class/function/ID
1. The first segment represents the controller class that should be invoked.
2. The second segment represents the class function, or method, that should be called.
3. The third, and any additional segments, represent the ID and any variables that will be passed to the controller.
The URI Library and the URL Helper contain functions that make it easy to work with your URI data. In addition,
your URLs can be remapped using the URI Routing feature for more flexibility.
Removing the index.php file
By default, the index.php file will be included in your URLs:
example.com/index.php/news/article/my_article
If your Apache server has mod_rewrite enabled, you can easily remove this file by using a .htaccess file with some
simple rules. Here is an example of such a file, using the “negative” method in which everything is redirected except
the specified items:
13
CodeIgniter Documentation, 3.0-dev
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
In the above example, any HTTP request other than those for existing directories and existing files is treated as a
request for your index.php file.
: These specific rules might not work for all server configurations.
: Make sure to also exclude from the above rule any assets that you might need to be accessible from the outside
world.
Adding a URL Suffix
In your config/config.php file you can specify a suffix that will be added to all URLs generated by CodeIgniter. For
example, if a URL is this:
example.com/index.php/products/view/shoes
You can optionally add a suffix, like .html, making the page appear to be of a certain type:
example.com/index.php/products/view/shoes.html
Enabling Query Strings
In some cases you might prefer to use query strings URLs:
index.php?c=products&m=view&id=345
CodeIgniter optionally supports this capability, which can be enabled in your application/config.php file. If you open
your config file you’ll see these items:
$config[’enable_query_strings’] = FALSE;
$config[’controller_trigger’] = ’c’;
$config[’function_trigger’] = ’m’;
If you change “enable_query_strings” to TRUE this feature will become active. Your controllers and functions will
then be accessible using the “trigger” words you’ve set to invoke your controllers and methods:
index.php?c=controller&m=method
: If you are using query strings you will have to build your own URLs, rather than utilizing the URL helpers (and
other helpers that generate URLs, like some of the form helpers) as these are designed to work with segment based
URLs.
6.1.2 Controllers
Controllers are the heart of your application, as they determine how HTTP requests should be handled.
14
Chapter 6.
CodeIgniter Documentation, 3.0-dev
Page Contents
• Controllers
– What is a Controller?
– Let’s try it: Hello World!
– Methods
– Passing URI Segments to your methods
– Defining a Default Controller
– Remapping Method Calls
– Processing Output
– Private methods
– Organizing Your Controllers into Sub-directories
– Class Constructors
– Reserved method names
– That’s it!
What is a Controller?
A Controller is simply a class file that is named in a way that can be associated with a URI.
Consider this URI:
example.com/index.php/blog/
In the above example, CodeIgniter would attempt to find a controller named Blog.php and load it.
When a controller’s name matches the first segment of a URI, it will be loaded.
Let’s try it: Hello World!
Let’s create a simple controller so you can see it in action. Using your text editor, create a file called Blog.php, and
put the following code in it:
<?php
class Blog extends CI_Controller {
public function index()
{
echo ’Hello World!’;
}
}
Then save the file to your application/controllers/ directory.
: The file must be called ‘Blog.php’, with a capital ‘B’.
Now visit the your site using a URL similar to this:
example.com/index.php/blog/
If you did it right, you should see:
Hello World!
6.1. General Topics
15
CodeIgniter Documentation, 3.0-dev
: Class names must start with an uppercase letter.
This is valid:
<?php
class Blog extends CI_Controller {
}
This is not valid:
<?php
class blog extends CI_Controller {
}
Also, always make sure your controller extends the parent controller class so that it can inherit all its methods.
Methods
In the above example the method name is index(). The “index” method is always loaded by default if the second
segment of the URI is empty. Another way to show your “Hello World” message would be this:
example.com/index.php/blog/index/
The second segment of the URI determines which method in the controller gets called.
Let’s try it. Add a new method to your controller:
<?php
class Blog extends CI_Controller {
public function index()
{
echo ’Hello World!’;
}
public function comments()
{
echo ’Look at this!’;
}
}
Now load the following URL to see the comment method:
example.com/index.php/blog/comments/
You should see your new message.
Passing URI Segments to your methods
If your URI contains more then two segments they will be passed to your method as parameters.
For example, let’s say you have a URI like this:
example.com/index.php/products/shoes/sandals/123
16
Chapter 6.
CodeIgniter Documentation, 3.0-dev
Your method will be passed URI segments 3 and 4 (“sandals” and “123”):
<?php
class Products extends CI_Controller {
public function shoes($sandals, $id)
{
echo $sandals;
echo $id;
}
}
: If you are using the URI Routing feature, the segments passed to your method will be the re-routed ones.
Defining a Default Controller
CodeIgniter can be told to load a default controller when a URI is not present, as will be the case when only your
site root URL is requested. To specify a default controller, open your application/config/routes.php file and set this
variable:
$route[’default_controller’] = ’Blog’;
Where Blog is the name of the controller class you want used. If you now load your main index.php file without
specifying any URI segments you’ll see your Hello World message by default.
Remapping Method Calls
As noted above, the second segment of the URI typically determines which method in the controller gets called.
CodeIgniter permits you to override this behavior through the use of the _remap() method:
public function _remap()
{
// Some code here...
}
: If your controller contains a method named _remap(), it will always get called regardless of what your URI contains.
It overrides the normal behavior in which the URI determines which method is called, allowing you to define your
own method routing rules.
The overridden method call (typically the second segment of the URI) will be passed as a parameter to the _remap()
method:
public function _remap($method)
{
if ($method === ’some_method’)
{
$this->$method();
}
else
{
$this->default_method();
}
}
6.1. General Topics
17
CodeIgniter Documentation, 3.0-dev
Any extra segments after the method name are passed into _remap() as an optional second parameter. This array
can be used in combination with PHP’s call_user_func_array() to emulate CodeIgniter’s default behavior.
Example:
public function _remap($method, $params = array())
{
$method = ’process_’.$method;
if (method_exists($this, $method))
{
return call_user_func_array(array($this, $method), $params);
}
show_404();
}
Processing Output
CodeIgniter has an output class that takes care of sending your final rendered data to the web browser automatically.
More information on this can be found in the Views and Output Class pages. In some cases, however, you might want
to post-process the finalized data in some way and send it to the browser yourself. CodeIgniter permits you to add a
method named _output() to your controller that will receive the finalized output data.
: If your controller contains a method named _output(), it will always be called by the output class instead of
echoing the finalized data directly. The first parameter of the method will contain the finalized output.
Here is an example:
public function _output($output)
{
echo $output;
}
: Please note that your _output() method will receive the data in its finalized state. Benchmark and memory
usage data will be rendered, cache files written (if you have caching enabled), and headers will be sent (if you use
that feature) before it is handed off to the _output() method. To have your controller’s output cached properly, its
_output() method can use:
if ($this->output->cache_expiration > 0)
{
$this->output->_write_cache($output);
}
If you are using this feature the page execution timer and memory usage stats might not be perfectly accurate since
they will not take into account any further processing you do. For an alternate way to control output before any of the
final processing is done, please see the available methods in the Output Library.
Private methods
In some cases you may want certain methods hidden from public access. In order to achieve this, simply declare the
method as being private or protected and it will not be served via a URL request. For example, if you were to have a
method like this:
private function _utility()
{
18
Chapter 6.
CodeIgniter Documentation, 3.0-dev
// some code
}
Trying to access it via the URL, like this, will not work:
example.com/index.php/blog/_utility/
: Prefixing method names with an underscore will also prevent them from being called. This is a legacy feature that
is left for backwards-compatibility.
Organizing Your Controllers into Sub-directories
If you are building a large application you might find it convenient to organize your controllers into sub-directories.
CodeIgniter permits you to do this.
Simply create folders within your application/controllers/ directory and place your controller classes within them.
: When using this feature the first segment of your URI must specify the folder. For example, let’s say you have a
controller located here:
application/controllers/products/Shoes.php
To call the above controller your URI will look something like this:
example.com/index.php/products/shoes/show/123
Each of your sub-directories may contain a default controller which will be called if the URL contains only the subfolder. Simply name your default controller as specified in your application/config/routes.php file.
CodeIgniter also permits you to remap your URIs using its URI Routing feature.
Class Constructors
If you intend to use a constructor in any of your Controllers, you MUST place the following line of code in it:
parent::__construct();
The reason this line is necessary is because your local constructor will be overriding the one in the parent controller
class so we need to manually call it.
Example:
<?php
class Blog extends CI_Controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
}
}
Constructors are useful if you need to set some default values, or run a default process when your class is instantiated.
Constructors can’t return a value, but they can do some default work.
6.1. General Topics
19
CodeIgniter Documentation, 3.0-dev
Reserved method names
Since your controller classes will extend the main application controller you must be careful not to name your methods
identically to the ones used by that class, otherwise your local functions will override them. See Reserved Names for
a full list.
:
You should also never have a method named identically to its class name. If you do, and there is no
__construct() method in the same class, then your e.g. Index::index() method will be executed as a
class constructor! This is a PHP4 backwards-compatibility feature.
That’s it!
That, in a nutshell, is all there is to know about controllers.
6.1.3 Reserved Names
In order to help out, CodeIgniter uses a series of function, method, class and variable names in its operation. Because
of this, some names cannot be used by a developer. Following is a list of reserved names that cannot be used.
Controller names
Since your controller classes will extend the main application controller you must be careful not to name your methods
identically to the ones used by that class, otherwise your local methods will override them. The following is a list of
reserved names. Do not name your controller any of these:
• Controller
• CI_Base
• _ci_initialize
• Default
• index
Functions
• is_php()
• is_really_writable()
• load_class()
• is_loaded()
• get_config()
• config_item()
• show_error()
• show_404()
• log_message()
• set_status_header()
• get_mimes()
20
Chapter 6.
CodeIgniter Documentation, 3.0-dev
• html_escape()
• remove_invisible_characters()
• is_https()
• function_usable()
• get_instance()
• _exception_handler()
• _stringify_attributes()
Variables
• $config
• $db
• $lang
Constants
• ENVIRONMENT
• FCPATH
• SELF
• BASEPATH
• APPPATH
• VIEWPATH
• CI_VERSION
• FILE_READ_MODE
• FILE_WRITE_MODE
• DIR_READ_MODE
• DIR_WRITE_MODE
• FOPEN_READ
• FOPEN_READ_WRITE
• FOPEN_WRITE_CREATE_DESTRUCTIVE
• FOPEN_READ_WRITE_CREATE_DESTRUCTIVE
• FOPEN_WRITE_CREATE
• FOPEN_READ_WRITE_CREATE
• FOPEN_WRITE_CREATE_STRICT
• FOPEN_READ_WRITE_CREATE_STRICT
• EXIT_SUCCESS
• EXIT_ERROR
• EXIT_CONFIG
6.1. General Topics
21
CodeIgniter Documentation, 3.0-dev
• EXIT_UNKNOWN_FILE
• EXIT_UNKNOWN_CLASS
• EXIT_UNKNOWN_METHOD
• EXIT_USER_INPUT
• EXIT_DATABASE
• EXIT__AUTO_MIN
• EXIT__AUTO_MAX
6.1.4 Views
A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be
embedded within other views (within other views, etc., etc.) if you need this type of hierarchy.
Views are never called directly, they must be loaded by a controller. Remember that in an MVC framework, the
Controller acts as the traffic cop, so it is responsible for fetching a particular view. If you have not read the Controllers
page you should do so before continuing.
Using the example controller you created in the controller page, let’s add a view to it.
Creating a View
Using your text editor, create a file called blogview.php, and put this in it:
<html>
<head>
<title>My Blog</title>
</head>
<body>
<h1>Welcome to my Blog!</h1>
</body>
</html>
Then save the file in your application/views/ directory.
Loading a View
To load a particular view file you will use the following method:
$this->load->view(’name’);
Where name is the name of your view file.
: The .php file extension does not need to be specified unless you use something other than .php.
Now, open the controller file you made earlier called Blog.php, and replace the echo statement with the view loading
method:
<?php
class Blog extends CI_Controller {
public function index()
{
22
Chapter 6.
CodeIgniter Documentation, 3.0-dev
$this->load->view(’blogview’);
}
}
If you visit your site using the URL you did earlier you should see your new view. The URL was similar to this:
example.com/index.php/blog/
Loading multiple views
CodeIgniter will intelligently handle multiple calls to $this->load->view() from within a controller. If more
than one call happens they will be appended together. For example, you may wish to have a header view, a menu view,
a content view, and a footer view. That might look something like this:
<?php
class Page extends CI_Controller {
public function index()
{
$data[’page_title’] = ’Your title’;
$this->load->view(’header’);
$this->load->view(’menu’);
$this->load->view(’content’, $data);
$this->load->view(’footer’);
}
}
In the example above, we are using “dynamically added data”, which you will see below.
Storing Views within Sub-directories
Your view files can also be stored within sub-directories if you prefer that type of organization. When doing so you
will need to include the directory name loading the view. Example:
$this->load->view(’directory_name/file_name’);
Adding Dynamic Data to the View
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view
loading method. Here is an example using an array:
$data = array(
’title’ => ’My Title’,
’heading’ => ’My Heading’,
’message’ => ’My Message’
);
$this->load->view(’blogview’, $data);
And here’s an example using an object:
$data = new Someclass();
$this->load->view(’blogview’, $data);
6.1. General Topics
23
CodeIgniter Documentation, 3.0-dev
: If you use an object, the class variables will be turned into array elements.
Let’s try it with your controller file. Open it add this code:
<?php
class Blog extends CI_Controller {
public function index()
{
$data[’title’] = "My Real Title";
$data[’heading’] = "My Real Heading";
$this->load->view(’blogview’, $data);
}
}
Now open your view file and change the text to variables that correspond to the array keys in your data:
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
</body>
</html>
Then load the page at the URL you’ve been using and you should see the variables replaced.
Creating Loops
The data array you pass to your view files is not limited to simple variables. You can pass multi dimensional arrays,
which can be looped to generate multiple rows. For example, if you pull data from your database it will typically be
in the form of a multi-dimensional array.
Here’s a simple example. Add this to your controller:
<?php
class Blog extends CI_Controller {
public function index()
{
$data[’todo_list’] = array(’Clean House’, ’Call Mom’, ’Run Errands’);
$data[’title’] = "My Real Title";
$data[’heading’] = "My Real Heading";
$this->load->view(’blogview’, $data);
}
}
Now open your view file and create a loop:
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
24
Chapter 6.
CodeIgniter Documentation, 3.0-dev
<h1><?php echo $heading;?></h1>
<h3>My Todo List</h3>
<ul>
<?php foreach ($todo_list as $item):?>
<li><?php echo $item;?></li>
<?php endforeach;?>
</ul>
</body>
</html>
: You’ll notice that in the example above we are using PHP’s alternative syntax. If you are not familiar with it you
can read about it here.
Returning views as data
There is a third optional parameter lets you change the behavior of the method so that it returns data as a string rather
than sending it to your browser. This can be useful if you want to process the data in some way. If you set the parameter
to TRUE (boolean) it will return data. The default behavior is false, which sends it to your browser. Remember to
assign it to a variable if you want the data returned:
$string = $this->load->view(’myfile’, ’’, TRUE);
6.1.5 Models
Models are optionally available for those who want to use a more traditional MVC approach.
Page Contents
• Models
– What is a Model?
– Anatomy of a Model
– Loading a Model
– Auto-loading Models
– Connecting to your Database
What is a Model?
Models are PHP classes that are designed to work with information in your database. For example, let’s say you use
CodeIgniter to manage a blog. You might have a model class that contains functions to insert, update, and retrieve
your blog data. Here is an example of what such a model class might look like:
class Blog_model extends CI_Model {
public $title;
public $content;
public $date;
6.1. General Topics
25
CodeIgniter Documentation, 3.0-dev
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
public function get_last_ten_entries()
{
$query = $this->db->get(’entries’, 10);
return $query->result();
}
public function insert_entry()
{
$this->title
= $_POST[’title’]; // please read the below note
$this->content = $_POST[’content’];
$this->date
= time();
$this->db->insert(’entries’, $this);
}
public function update_entry()
{
$this->title
= $_POST[’title’];
$this->content = $_POST[’content’];
$this->date
= time();
$this->db->update(’entries’, $this, array(’id’ => $_POST[’id’]));
}
}
: The methods in the above example use the Query Builder database methods.
: For the sake of simplicity in this example we’re using $_POST directly. This is generally bad practice, and a more
common approach would be to use the Input Library $this->input->post(’title’).
Anatomy of a Model
Model classes are stored in your application/models/ directory. They can be nested within sub-directories if you want
this type of organization.
The basic prototype for a model class is this:
class Model_name extends CI_Model {
public function __construct()
{
parent::__construct();
}
}
Where Model_name is the name of your class. Class names must have the first letter capitalized with the rest of the
name lowercase. Make sure your class extends the base Model class.
26
Chapter 6.
CodeIgniter Documentation, 3.0-dev
The file name must match the class name. For example, if this is your class:
class User_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
}
Your file will be this:
application/models/User_model.php
Loading a Model
Your models will typically be loaded and called from within your controller methods. To load a model you will use
the following method:
$this->load->model(’model_name’);
If your model is located in a sub-directory, include the relative path from your models directory. For example, if you
have a model located at application/models/blog/Queries.php you’ll load it using:
$this->load->model(’blog/queries’);
Once loaded, you will access your model methods using an object with the same name as your class:
$this->load->model(’model_name’);
$this->model_name->method();
If you would like your model assigned to a different object name you can specify it via the second parameter of the
loading method:
$this->load->model(’model_name’, ’foobar’);
$this->foobar->method();
Here is an example of a controller, that loads a model, then serves a view:
class Blog_controller extends CI_Controller {
public function blog()
{
$this->load->model(’blog’);
$data[’query’] = $this->Blog->get_last_ten_entries();
$this->load->view(’blog’, $data);
}
}
Auto-loading Models
If you find that you need a particular model globally throughout your application, you can tell CodeIgniter to autoload it during system initialization. This is done by opening the application/config/autoload.php file and adding the
6.1. General Topics
27
CodeIgniter Documentation, 3.0-dev
model to the autoload array.
Connecting to your Database
When a model is loaded it does NOT connect automatically to your database. The following options for connecting
are available to you:
• You can connect using the standard database methods described here, either from within your Controller class
or your Model class.
• You can tell the model loading method to auto-connect by passing TRUE (boolean) via the third parameter, and
connectivity settings, as defined in your database config file will be used:
$this->load->model(’model_name’, ’’, TRUE);
• You can manually pass database connectivity settings via the third parameter:
$config[’hostname’]
$config[’username’]
$config[’password’]
$config[’database’]
$config[’dbdriver’]
$config[’dbprefix’]
$config[’pconnect’]
$config[’db_debug’]
=
=
=
=
=
=
=
=
’localhost’;
’myusername’;
’mypassword’;
’mydatabase’;
’mysqli’;
’’;
FALSE;
TRUE;
$this->load->model(’model_name’, ’’, $config);
6.1.6 Helper Functions
Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular
category. There are URL Helpers, that assist in creating links, there are Form Helpers that help you create form
elements, Text Helpers perform various text formatting routines, Cookie Helpers set and read cookies, File Helpers
help you deal with files, etc.
Unlike most other systems in CodeIgniter, Helpers are not written in an Object Oriented format. They are simple,
procedural functions. Each helper function performs one specific task, with no dependence on other functions.
CodeIgniter does not load Helper Files by default, so the first step in using a Helper is to load it. Once loaded, it
becomes globally available in your controller and views.
Helpers are typically stored in your system/helpers, or application/helpers directory. CodeIgniter will look first in
your application/helpers directory. If the directory does not exist or the specified helper is not located there CI will
instead look in your global system/helpers/ directory.
Loading a Helper
Loading a helper file is quite simple using the following method:
$this->load->helper(’name’);
Where name is the file name of the helper, without the .php file extension or the “helper” part.
For example, to load the URL Helper file, which is named url_helper.php, you would do this:
$this->load->helper(’url’);
28
Chapter 6.
CodeIgniter Documentation, 3.0-dev
A helper can be loaded anywhere within your controller methods (or even within your View files, although that’s not
a good practice), as long as you load it before you use it. You can load your helpers in your controller constructor so
that they become available automatically in any function, or you can load a helper in a specific function that needs it.
: The Helper loading method above does not return a value, so don’t try to assign it to a variable. Just use it as shown.
Loading Multiple Helpers
If you need to load more than one helper you can specify them in an array, like this:
$this->load->helper(
array(’helper1’, ’helper2’, ’helper3’)
);
Auto-loading Helpers
If you find that you need a particular helper globally throughout your application, you can tell CodeIgniter to autoload it during system initialization. This is done by opening the application/config/autoload.php file and adding the
helper to the autoload array.
Using a Helper
Once you’ve loaded the Helper File containing the function you intend to use, you’ll call it the way you would a
standard PHP function.
For example, to create a link using the anchor() function in one of your view files you would do this:
<?php echo anchor(’blog/comments’, ’Click Here’);?>
Where “Click Here” is the name of the link, and “blog/comments” is the URI to the controller/method you wish to
link to.
“Extending” Helpers
To “extend” Helpers, create a file in your application/helpers/ folder with an identical name to the existing Helper,
but prefixed with MY_ (this item is configurable. See below.).
If all you need to do is add some functionality to an existing helper - perhaps add a function or two, or change how
a particular helper function operates - then it’s overkill to replace the entire helper with your version. In this case it’s
better to simply “extend” the Helper.
: The term “extend” is used loosely since Helper functions are procedural and discrete and cannot be extended in the
traditional programmatic sense. Under the hood, this gives you the ability to add to or or to replace the functions a
Helper provides.
For example,
to extend the native Array Helper you’ll
tion/helpers/MY_array_helper.php, and add or override functions:
create
a
file
named
applica-
// any_in_array() is not in the Array Helper, so it defines a new function
function any_in_array($needle, $haystack)
{
$needle = is_array($needle) ? $needle : array($needle);
6.1. General Topics
29
CodeIgniter Documentation, 3.0-dev
foreach ($needle as $item)
{
if (in_array($item, $haystack))
{
return TRUE;
}
}
return FALSE;
}
// random_element() is included in Array Helper, so it overrides the native function
function random_element($array)
{
shuffle($array);
return array_pop($array);
}
Setting Your Own Prefix
The filename prefix for “extending” Helpers is the same used to extend libraries and core classes. To set your own
prefix, open your application/config/config.php file and look for this item:
$config[’subclass_prefix’] = ’MY_’;
Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.
Now What?
In the Table of Contents you’ll find a list of all the available Helper Files. Browse each one to see what they do.
6.1.7 Using CodeIgniter Libraries
All of the available libraries are located in your system/libraries/ directory. In most cases, to use one of these classes
involves initializing it within a controller using the following initialization method:
$this->load->library(’class_name’);
Where ‘class_name’ is the name of the class you want to invoke. For example, to load the Form Validation Library
you would do this:
$this->load->library(’form_validation’);
Once initialized you can use it as indicated in the user guide page corresponding to that class.
Additionally, multiple libraries can be loaded at the same time by passing an array of libraries to the load method.
Example:
$this->load->library(array(’email’, ’table’));
Creating Your Own Libraries
Please read the section of the user guide that discusses how to create your own libraries.
30
Chapter 6.
CodeIgniter Documentation, 3.0-dev
6.1.8 Creating Libraries
When we use the term “Libraries” we are normally referring to the classes that are located in the libraries directory
and described in the Class Reference of this user guide. In this case, however, we will instead describe how you can
create your own libraries within your application/libraries directory in order to maintain separation between your local
resources and the global framework resources.
As an added bonus, CodeIgniter permits your libraries to extend native classes if you simply need to add some functionality to an existing library. Or you can even replace native libraries just by placing identically named versions in
your application/libraries directory.
In summary:
• You can create entirely new libraries.
• You can extend native libraries.
• You can replace native libraries.
The page below explains these three concepts in detail.
: The Database classes can not be extended or replaced with your own classes. All other classes are able to be
replaced/extended.
Storage
Your library classes should be placed within your application/libraries directory, as this is where CodeIgniter will look
for them when they are initialized.
Naming Conventions
• File names must be capitalized. For example: Myclass.php
• Class declarations must be capitalized. For example: class Myclass
• Class names and file names must match.
The Class File
Classes should have this basic prototype:
<?php if ( ! defined(’BASEPATH’)) exit(’No direct script access allowed’);
class Someclass {
public function some_method()
{
}
}
/* End of file Someclass.php */
: We are using the name Someclass purely as an example.
6.1. General Topics
31
CodeIgniter Documentation, 3.0-dev
Using Your Class
From within any of your Controller methods you can initialize your class using the standard:
$this->load->library(’someclass’);
Where someclass is the file name, without the ”.php” file extension. You can submit the file name capitalized or lower
case. CodeIgniter doesn’t care.
Once loaded you can access your class using the lower case version:
$this->someclass->some_method();
// Object instances will always be lower case
Passing Parameters When Initializing Your Class
In the library loading method you can dynamically pass data as an array via the second parameter and it will be passed
to your class constructor:
$params = array(’type’ => ’large’, ’color’ => ’red’);
$this->load->library(’someclass’, $params);
If you use this feature you must set up your class constructor to expect data:
<?php defined(’BASEPATH’) OR exit(’No direct script access allowed’);
class Someclass {
public function __construct($params)
{
// Do something with $params
}
}
You can also pass parameters stored in a config file. Simply create a config file named identically to the class file name
and store it in your application/config/ directory. Note that if you dynamically pass parameters as described above,
the config file option will not be available.
Utilizing CodeIgniter Resources within Your Library
To access CodeIgniter’s native resources within your library use the get_instance() method. This method returns
the CodeIgniter super object.
Normally from within your controller methods you will call any of the available CodeIgniter methods using the $this
construct:
$this->load->helper(’url’);
$this->load->library(’session’);
$this->config->item(’base_url’);
// etc.
$this, however, only works directly within your controllers, your models, or your views. If you would like to use
CodeIgniter’s classes from within your own custom classes you can do so as follows:
First, assign the CodeIgniter object to a variable:
$CI =& get_instance();
32
Chapter 6.
CodeIgniter Documentation, 3.0-dev
Once you’ve assigned the object to a variable, you’ll use that variable instead of $this:
$CI =& get_instance();
$CI->load->helper(’url’);
$CI->load->library(’session’);
$CI->config->item(’base_url’);
// etc.
: You’ll notice that the above get_instance() function is being passed by reference:
$CI =& get_instance();
This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a
copy of it.
However, since a library is a class, it would be better if you take full advantage of the OOP principles. So, in order
to be able to use the CodeIgniter super-object in all of the class methods, you’re encouraged to assign it to a property
instead:
class Example_library {
protected $CI;
// We’ll use a constructor, as you can’t directly call a function
// from a property definition.
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
}
public function foo()
{
$this->CI->load->helper(’url’);
redirect();
}
public function bar()
{
echo $this->CI->config_item(’base_url’);
}
}
Replacing Native Libraries with Your Versions
Simply by naming your class files identically to a native library will cause CodeIgniter to use it instead of the native
one. To use this feature you must name the file and the class declaration exactly the same as the native library. For
example, to replace the native Email library you’ll create a file named application/libraries/Email.php, and declare
your class with:
class CI_Email {
}
Note that most native classes are prefixed with CI_.
6.1. General Topics
33
CodeIgniter Documentation, 3.0-dev
To load your library you’ll see the standard loading method:
$this->load->library(’email’);
: At this time the Database classes can not be replaced with your own versions.
Extending Native Libraries
If all you need to do is add some functionality to an existing library - perhaps add a method or two - then it’s overkill
to replace the entire library with your version. In this case it’s better to simply extend the class. Extending a class is
nearly identical to replacing a class with a couple exceptions:
• The class declaration must extend the parent class.
• Your new class name and filename must be prefixed with MY_ (this item is configurable. See below.).
For example, to extend the native Email class you’ll create a file named application/libraries/MY_Email.php, and
declare your class with:
class MY_Email extends CI_Email {
}
If you need to use a constructor in your class make sure you extend the parent constructor:
class MY_Email extends CI_Email {
public function __construct($config = array())
{
parent::__construct($config);
}
}
: Not all of the libraries have the same (or any) parameters in their constructor. Take a look at the library that you’re
extending first to see how it should be implemented.
Loading Your Sub-class
To load your sub-class you’ll use the standard syntax normally used. DO NOT include your prefix. For example, to
load the example above, which extends the Email class, you will use:
$this->load->library(’email’);
Once loaded you will use the class variable as you normally would for the class you are extending. In the case of the
email class all calls will use:
$this->email->some_method();
Setting Your Own Prefix
To set your own sub-class prefix, open your application/config/config.php file and look for this item:
34
Chapter 6.
CodeIgniter Documentation, 3.0-dev
$config[’subclass_prefix’] = ’MY_’;
Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.
6.1.9 Using CodeIgniter Drivers
Drivers are a special type of Library that has a parent class and any number of potential child classes. Child classes
have access to the parent class, but not their siblings. Drivers provide an elegant syntax in your controllers for libraries
that benefit from or require being broken down into discrete classes.
Drivers are found in the system/libraries/ directory, in their own sub-directory which is identically named to the parent
library class. Also inside that directory is a subdirectory named drivers, which contains all of the possible child class
files.
To use a driver you will initialize it within a controller using the following initialization method:
$this->load->driver(’class_name’);
Where class name is the name of the driver class you want to invoke. For example, to load a driver named
“Some_parent” you would do this:
$this->load->driver(’some_parent’);
Methods of that class can then be invoked with:
$this->some_parent->some_method();
The child classes, the drivers themselves, can then be called directly through the parent class, without initializing them:
$this->some_parent->child_one->some_method();
$this->some_parent->child_two->another_method();
Creating Your Own Drivers
Please read the section of the user guide that discusses how to create your own drivers.
6.1.10 Creating Drivers
Driver Directory and File Structure
Sample driver directory and file structure layout:
• /application/libraries/Driver_name
– Driver_name.php
– drivers
* Driver_name_subclass_1.php
* Driver_name_subclass_2.php
* Driver_name_subclass_3.php
: In order to maintain compatibility on case-sensitive file systems, the Driver_name directory must be named in the
format returned by ucfirst().
6.1. General Topics
35
CodeIgniter Documentation, 3.0-dev
6.1.11 Creating Core System Classes
Every time CodeIgniter runs there are several base classes that are initialized automatically as part of the core framework. It is possible, however, to swap any of the core system classes with your own versions or even extend the core
versions.
Most users will never have any need to do this, but the option to replace or extend them does exist for those who
would like to significantly alter the CodeIgniter core.
: Messing with a core system class has a lot of implications, so make sure you know what you are doing before
attempting it.
System Class List
The following is a list of the core system files that are invoked every time CodeIgniter runs:
• Benchmark
• Config
• Controller
• Exceptions
• Hooks
• Input
• Language
• Loader
• Log
• Output
• Router
• Security
• URI
• Utf8
Replacing Core Classes
To use one of your own system classes instead of a default one simply place your version inside your local application/core/ directory:
application/core/some_class.php
If this directory does not exist you can create it.
Any file named identically to one from the list above will be used instead of the one normally used.
Please note that your class must use CI as a prefix. For example, if your file is named Input.php the class will be
named:
class CI_Input {
}
36
Chapter 6.
CodeIgniter Documentation, 3.0-dev
Extending Core Class
If all you need to do is add some functionality to an existing library - perhaps add a method or two - then it’s overkill
to replace the entire library with your version. In this case it’s better to simply extend the class. Extending a class is
nearly identical to replacing a class with a couple exceptions:
• The class declaration must extend the parent class.
• Your new class name and filename must be prefixed with MY_ (this item is configurable. See below.).
For example, to extend the native Input class you’ll create a file named application/core/MY_Input.php, and declare
your class with:
class MY_Input extends CI_Input {
}
: If you need to use a constructor in your class make sure you extend the parent constructor:
class MY_Input extends CI_Input {
public function __construct()
{
parent::__construct();
}
}
Tip: Any functions in your class that are named identically to the methods in the parent class will be used instead of
the native ones (this is known as “method overriding”). This allows you to substantially alter the CodeIgniter core.
If you are extending the Controller core class, then be sure to extend your new class in your application controller’s
constructors.
class Welcome extends MY_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view(’welcome_message’);
}
}
Setting Your Own Prefix
To set your own sub-class prefix, open your application/config/config.php file and look for this item:
$config[’subclass_prefix’] = ’MY_’;
Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.
6.1. General Topics
37
CodeIgniter Documentation, 3.0-dev
6.1.12 Creating Ancillary Classes
In some cases you may want to develop classes that exist apart from your controllers but have the ability to utilize all
of CodeIgniter’s resources. This is easily possible as you’ll see.
get_instance()
get_instance()
object of class CI_Controller
Any class that you instantiate within your controller methods can access CodeIgniter’s native resources simply
by using the get_instance() function. This function returns the main CodeIgniter object.
Normally, to call any of the available CodeIgniter methods requires you to use the $this construct:
$this->load->helper(’url’);
$this->load->library(’session’);
$this->config->item(’base_url’);
// etc.
$this, however, only works within your controllers, your models, or your views. If you would like to use
CodeIgniter’s classes from within your own custom classes you can do so as follows:
First, assign the CodeIgniter object to a variable:
$CI =& get_instance();
Once you’ve assigned the object to a variable, you’ll use that variable instead of $this:
$CI =& get_instance();
$CI->load->helper(’url’);
$CI->load->library(’session’);
$CI->config->item(’base_url’);
// etc.
: You’ll notice that the above get_instance() function is being passed by reference:
$CI =& get_instance();
This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a
copy of it.
Furthermore, if you’ll be using get_intance() inside anoter class, then it would be better if you assign it to a
property. This way, you won’t need to call get_instance() in every single method.
Example:
class Example {
protected $CI;
// We’ll use a constructor, as you can’t directly call a function
// from a property definition.
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
38
Chapter 6.
CodeIgniter Documentation, 3.0-dev
}
public function foo()
{
$this->CI->load->helper(’url’);
redirect();
}
public function bar()
{
$this->CI->config_item(’base_url’);
}
}
In the above example, both methods foo() and bar() will work after you instantiate the Example class, without
the need to call get_instance() in each of them.
6.1.13 Hooks - Extending the Framework Core
CodeIgniter’s Hooks feature provides a means to tap into and modify the inner workings of the framework without
hacking the core files. When CodeIgniter runs it follows a specific execution process, diagramed in the Application
Flow page. There may be instances, however, where you’d like to cause some action to take place at a particular stage
in the execution process. For example, you might want to run a script right before your controllers get loaded, or right
after, or you might want to trigger one of your own scripts in some other location.
Enabling Hooks
The hooks feature can be globally enabled/disabled by setting the following item in the application/config/config.php
file:
$config[’enable_hooks’] = TRUE;
Defining a Hook
Hooks are defined in application/config/hooks.php file. Each hook is specified as an array with this prototype:
$hook[’pre_controller’] = array(
’class’
=> ’MyClass’,
’function’ => ’Myfunction’,
’filename’ => ’Myclass.php’,
’filepath’ => ’hooks’,
’params’
=> array(’beer’, ’wine’, ’snacks’)
);
Notes:
The array index correlates to the name of the particular hook point you want to use. In the above example the hook
point is pre_controller. A list of hook points is found below. The following items should be defined in your associative
hook array:
• class The name of the class you wish to invoke. If you prefer to use a procedural function instead of a class,
leave this item blank.
• function The function (or method) name you wish to call.
6.1. General Topics
39
CodeIgniter Documentation, 3.0-dev
• filename The file name containing your class/function.
• filepath The name of the directory containing your script. Note: Your script must be located in a directory
INSIDE your application/ directory, so the file path is relative to that directory. For example, if your script is
located in application/hooks/, you will simply use ‘hooks’ as your filepath. If your script is located in application/hooks/utilities/ you will use ‘hooks/utilities’ as your filepath. No trailing slash.
• params Any parameters you wish to pass to your script. This item is optional.
Multiple Calls to the Same Hook
If want to use the same hook point with more then one script, simply make your array declaration multi-dimensional,
like this:
$hook[’pre_controller’][] = array(
’class’
=> ’MyClass’,
’function’ => ’MyMethod’,
’filename’ => ’Myclass.php’,
’filepath’ => ’hooks’,
’params’
=> array(’beer’, ’wine’, ’snacks’)
);
$hook[’pre_controller’][] = array(
’class’
=> ’MyOtherClass’,
’function’ => ’MyOtherMethod’,
’filename’ => ’Myotherclass.php’,
’filepath’ => ’hooks’,
’params’
=> array(’red’, ’yellow’, ’blue’)
);
Notice the brackets after each array index:
$hook[’pre_controller’][]
This permits you to have the same hook point with multiple scripts. The order you define your array will be the
execution order.
Hook Points
The following is a list of available hook points.
• pre_system Called very early during system execution. Only the benchmark and hooks class have been loaded
at this point. No routing or other processes have happened.
• pre_controller Called immediately prior to any of your controllers being called. All base classes, routing, and
security checks have been done.
• post_controller_constructor Called immediately after your controller is instantiated, but prior to any method
calls happening.
• post_controller Called immediately after your controller is fully executed.
• display_override Overrides the _display() method, used to send the finalized page to the web browser at
the end of system execution. This permits you to use your own display methodology. Note that you will need
to reference the CI superobject with $this->CI =& get_instance() and then the finalized data will be
available by calling $this->CI->output->get_output().
• cache_override Enables you to call your own method instead of the _display_cache() method in the
Output Library. This permits you to use your own cache display mechanism.
40
Chapter 6.
CodeIgniter Documentation, 3.0-dev
• post_system Called after the final rendered page is sent to the browser, at the end of system execution after the
finalized data is sent to the browser.
6.1.14 Auto-loading Resources
CodeIgniter comes with an “Auto-load” feature that permits libraries, helpers, and models to be initialized automatically every time the system runs. If you need certain resources globally throughout your application you should
consider auto-loading them for convenience.
The following items can be loaded automatically:
• Classes found in the libraries/ directory
• Helper files found in the helpers/ directory
• Custom config files found in the config/ directory
• Language files found in the system/language/ directory
• Models found in the models/ folder
To autoload resources, open the application/config/autoload.php file and add the item you want loaded to the autoload
array. You’ll find instructions in that file corresponding to each type of item.
: Do not include the file extension (.php) when adding items to the autoload array.
6.1.15 Common Functions
CodeIgniter uses a few functions for its operation that are globally defined, and are available to you at any point. These
do not require loading any libraries or helpers.
is_php()
is_php($version = ‘5.3.0’)
• $version (string) – Version number
bool
Determines of the PHP version being used is greater than the supplied version number.
Example:
if (is_php(’5.3’))
{
$str = quoted_printable_encode($str);
}
Returns boolean TRUE if the installed version of PHP is equal to or greater than the supplied version number. Returns
FALSE if the installed version of PHP is lower than the supplied version number.
is_really_writable()
is_really_writable($file)
6.1. General Topics
41
CodeIgniter Documentation, 3.0-dev
• $file (string) – File path
bool
is_writable() returns TRUE on Windows servers when you really can’t write to the file as the OS reports to PHP
as FALSE only if the read-only attribute is marked.
This function determines if a file is actually writable by attempting to write to it first. Generally only recommended
on platforms where this information may be unreliable.
Example:
if (is_really_writable(’file.txt’))
{
echo "I could write to this if I wanted to";
}
else
{
echo "File is not writable";
}
config_item()
config_item($key)
• $key (string) – Config item key
mixed
The Config Library is the preferred way of accessing configuration information, however config_item() can be
used to retrieve single keys. See Config Library documentation for more information.
show_error()
show_error($message, $status_code, $heading = ‘An Error Was Encountered’)
• $message (mixed) – Error message
• $status_code (int) – HTTP Response status code
• $heading (string) – Error page heading
void
This function calls CI_Exception::show_error(). For more info, please see the Error Handling documentation.
show_404()
show_404($page = ‘’, $log_error = TRUE)
• $page (string) – URI string
• $log_error (bool) – Whether to log the error
void
42
Chapter 6.
CodeIgniter Documentation, 3.0-dev
This function calls CI_Exception::show_404(). For more info, please see the Error Handling documentation.
log_message()
log_message($level, $message)
• $level (string) – Log level: ‘error’, ‘debug’ or ‘info’
• $message (string) – Message to log
void
This function is an alias for CI_Log::write_log(). For more info, please see the Error Handling documentation.
set_status_header()
set_status_header($code, $text = ‘’)
• $code (int) – HTTP Reponse status code
• $text (string) – A custom message to set with the status code
void
Permits you to manually set a server status header. Example:
set_status_header(401);
// Sets the header as: Unauthorized
See here for a full list of headers.
remove_invisible_characters()
remove_invisible_characters($str, $url_encoded = TRUE)
• $str (string) – Input string
• $url_encoded (bool) – Whether to remove URL-encoded characters as well
string
This function prevents inserting NULL characters between ASCII characters, like Java\0script.
Example:
remove_invisible_characters(’Java\\0script’);
// Returns: ’Javascript’
html_escape()
html_escape($var)
• $var (mixed) – Variable to escape (string or array)
6.1. General Topics
43
CodeIgniter Documentation, 3.0-dev
mixed
This function acts as an alias for PHP’s native htmlspecialchars() function, with the advantage of being able
to accept an array of strings.
It is useful in preventing Cross Site Scripting (XSS).
get_mimes()
get_mimes()
array
This function returns a reference to the MIMEs array from application/config/mimes.php.
is_https()
is_https()
bool
Returns TRUE if a secure (HTTPS) connection is used and FALSE in any other case (including non-HTTP requests).
is_cli()
is_cli()
bool
Returns TRUE if the application is run through the command line and FALSE if not.
: This function checks both if the PHP_SAPI value is ‘cli’ or if the STDIN constant is defined.
function_usable()
function_usable($function_name)
• $function_name (string) – Function name
bool
Returns TRUE if a function exists and is usable, FALSE otherwise.
This function runs a function_exists() check and if the Suhosin extension <http://www.hardenedphp.net/suhosin/> is loaded, checks if it doesn’t disable the function being checked.
It is useful if you want to check for the availability of functions such as eval() and exec(), which are dangerous
and might be disabled on servers with highly restrictive security policies.
6.1.16 URI Routing
Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. The
segments in a URI normally follow this pattern:
44
Chapter 6.
CodeIgniter Documentation, 3.0-dev
example.com/class/function/id/
In some instances, however, you may want to remap this relationship so that a different class/method can be called
instead of the one corresponding to the URL.
For example, let’s say you want your URLs to have this prototype:
example.com/product/1/
example.com/product/2/
example.com/product/3/
example.com/product/4/
Normally the second segment of the URL is reserved for the method name, but in the example above it instead has a
product ID. To overcome this, CodeIgniter allows you to remap the URI handler.
Setting your own routing rules
Routing rules are defined in your application/config/routes.php file. In it you’ll see an array called $route that permits you to specify your own routing criteria. Routes can either be specified using wildcards or Regular Expressions.
Wildcards
A typical wildcard route might look something like this:
$route[’product/:num’] = ’catalog/product_lookup’;
In a route, the array key contains the URI to be matched, while the array value contains the destination it should be
re-routed to. In the above example, if the literal word “product” is found in the first segment of the URL, and a number
is found in the second segment, the “catalog” class and the “product_lookup” method are instead used.
You can match literal values or you can use two wildcard types:
(:num) will match a segment containing only numbers. (:any) will match a segment containing any character (except
for ‘/’, which is the segment delimiter).
: Wildcards are actually aliases for regular expressions, with :any being translated to [^/]+ and :num to [0-9]+,
respectively.
: Routes will run in the order they are defined. Higher routes will always take precedence over lower ones.
: Route rules are not filters! Setting a rule of e.g. ‘foo/bar/(:num)’ will not prevent controller Foo and method bar to
be called with a non-numeric value if that is a valid route.
Examples
Here are a few routing examples:
$route[’journals’] = ’blogs’;
A URL containing the word “journals” in the first segment will be remapped to the “blogs” class.
$route[’blog/joe’] = ’blogs/users/34’;
6.1. General Topics
45
CodeIgniter Documentation, 3.0-dev
A URL containing the segments blog/joe will be remapped to the “blogs” class and the “users” method. The ID will
be set to “34”.
$route[’product/(:any)’] = ’catalog/product_lookup’;
A URL with “product” as the first segment, and anything in the second will be remapped to the “catalog” class and the
“product_lookup” method.
$route[’product/(:num)’] = ’catalog/product_lookup_by_id/$1’;
A URL with “product” as the first segment, and a number in the second will be remapped to the “catalog” class and
the “product_lookup_by_id” method passing in the match as a variable to the method.
: Do not use leading/trailing slashes.
Regular Expressions
If you prefer you can use regular expressions to define your routing rules. Any valid regular expression is allowed, as
are back-references.
: If you use back-references you must use the dollar syntax rather than the double backslash syntax.
A typical RegEx route might look something like this:
$route[’products/([a-z]+)/(\d+)’] = ’$1/id_$2’;
In the above example, a URI similar to products/shirts/123 would instead call the “shirts” controller class and the
“id_123” method.
With regular expressions, you can also catch a segment containing a forward slash (‘/’), which would usually represent
the delimiter between multiple segments. For example, if a user accesses a password protected area of your web
application and you wish to be able to redirect them back to the same page after they log in, you may find this example
useful:
$route[’login/(.+)’] = ’auth/login/$1’;
That will call the “auth” controller class and its login() method, passing everything contained in the URI after
login/ as a parameter.
For those of you who don’t know regular expressions and want to learn more about them, regular-expressions.info
<http://www.regular-expressions.info/> might be a good starting point.
: You can also mix and match wildcards with regular expressions.
Callbacks
If you are using PHP >= 5.3 you can use callbacks in place of the normal routing rules to process the back-references.
Example:
$route[’products/([a-zA-Z]+)/edit/(\d+)’] = function ($product_type, $id)
{
return ’catalog/product_edit/’ . strtolower($product_type) . ’/’ . $id;
};
46
Chapter 6.
CodeIgniter Documentation, 3.0-dev
Using HTTP verbs in routes
It is possible to use HTTP verbs (request method) to define your routing rules. This is particularly useful when building
RESTful applications. You can use standard HTTP verbs (GET, PUT, POST, DELETE, PATCH) or a custom one such
(e.g. PURGE). HTTP verb rules are case-insensitive. All you need to do is to add the verb as an array key to your
route. Example:
$route[’products’][’put’] = ’product/insert’;
In the above example, a PUT request to URI “products” would call the Product::insert() controller method.
$route[’products/(:num)’][’DELETE’] = ’product/delete/$1’;
A DELETE request to URL with “products” as first the segment and a number in the second will be mapped to the
Product::delete() method, passing the numeric value as the first parameter.
Using HTTP verbs is of course, optional.
Reserved Routes
There are three reserved routes:
$route[’default_controller’] = ’welcome’;
This route indicates which controller class should be loaded if the URI contains no data, which will be the case when
people load your root URL. In the above example, the “welcome” class would be loaded. You are encouraged to
always have a default route otherwise a 404 page will appear by default.
$route[’404_override’] = ’’;
This route indicates which controller class should be loaded if the requested controller is not found. It will override
the default 404 error page. It won’t affect to the show_404() function, which will continue loading the default
error_404.php file at application/views/errors/error_404.php.
$route[’translate_uri_dashes’] = FALSE;
As evident by the boolean value, this is not exactly a route. This option enables you to automatically replace dashes
(‘-‘) with underscores in the controller and method URI segments, thus saving you additional route entries if you need
to do that. This is required, because the dash isn’t a valid class or method name character and would cause a fatal error
if you try to use it.
: The reserved routes must come before any wildcard or regular expression routes.
6.1.17 Error Handling
CodeIgniter lets you build error reporting into your applications using the functions described below. In addition, it
has an error logging class that permits error and debugging messages to be saved as text files.
: By default, CodeIgniter displays all PHP errors. You might wish to change this behavior once your development
is complete. You’ll find the error_reporting() function located at the top of your main index.php file. Disabling error
reporting will NOT prevent log files from being written if there are errors.
Unlike most systems in CodeIgniter, the error functions are simple procedural interfaces that are available globally
throughout the application. This approach permits error messages to get triggered without having to worry about
class/function scoping.
6.1. General Topics
47
CodeIgniter Documentation, 3.0-dev
CodeIgniter also returns a status code whenever a portion of the core calls exit(). This exit status code is separate
from the HTTP status code, and serves as a notice to other processes that may be watching of whether the script
completed successfully, or if not, what kind of problem it encountered that caused it to abort. These values are defined
in application/config/constants.php. While exit status codes are most useful in CLI settings, returning the proper code
helps server software keep track of your scripts and the health of your application.
The following functions let you generate errors:
show_error()
show_error($message, $status_code, $heading = ‘An Error Was Encountered’)
• $message (mixed) – Error message
• $status_code (int) – HTTP Response status code
• $heading (string) – Error page heading
void
This function will display the error message supplied to it using the following error template:
application/views/errors/error_general.php
The optional parameter $status_code determines what HTTP status code should be sent with the error. If
$status_code is less than 100, the HTTP status code will be set to 500, and the exit status code will be set to
$status_code + EXIT__AUTO_MIN. If that value is larger than EXIT__AUTO_MAX, or if $status_code
is 100 or higher, the exit status code will be set to EXIT_ERROR. You can check in application/config/constants.php
for more detail.
show_404()
show_404($page = ‘’, $log_error = TRUE)
• $page (string) – URI string
• $log_error (bool) – Whether to log the error
void
This function will display the 404 error message supplied to it using the following error template:
application/views/errors/error_404.php
The function expects the string passed to it to be the file path to the page that isn’t found. The exit status code will be
set to EXIT_UNKNOWN_FILE. Note that CodeIgniter automatically shows 404 messages if controllers are not found.
CodeIgniter automatically logs any show_404() calls. Setting the optional second parameter to FALSE will skip
logging.
log_message()
log_message($level, $message, $php_error = FALSE)
• $level (string) – Log level: ‘error’, ‘debug’ or ‘info’
48
Chapter 6.
CodeIgniter Documentation, 3.0-dev
• $message (string) – Message to log
• $php_error (bool) – Whether we’re logging a native PHP error message
void
This function lets you write messages to your log files. You must supply one of three “levels” in the first parameter,
indicating what type of message it is (debug, error, info), with the message itself in the second parameter.
Example:
if ($some_var == ’’)
{
log_message(’error’, ’Some variable did not contain a value.’);
}
else
{
log_message(’debug’, ’Some variable was correctly set’);
}
log_message(’info’, ’The purpose of some variable is to provide some value.’);
There are three message types:
1. Error Messages. These are actual errors, such as PHP errors or user errors.
2. Debug Messages. These are messages that assist in debugging. For example, if a class has been initialized, you
could log this as debugging info.
3. Informational Messages. These are the lowest priority messages, simply giving information regarding some
process. CodeIgniter doesn’t natively generate any info messages but you may want to in your application.
: In order for the log file to actually be written, the logs directory must be writable. In addition, you must set the
“threshold” for logging in application/config/config.php. You might, for example, only want error messages to be
logged, and not the other two types. If you set it to zero logging will be disabled.
6.1.18 Web Page Caching
CodeIgniter lets you cache your pages in order to achieve maximum performance.
Although CodeIgniter is quite fast, the amount of dynamic information you display in your pages will correlate directly
to the server resources, memory, and processing cycles utilized, which affect your page load speeds. By caching your
pages, since they are saved in their fully rendered state, you can achieve performance that nears that of static web
pages.
How Does Caching Work?
Caching can be enabled on a per-page basis, and you can set the length of time that a page should remain cached
before being refreshed. When a page is loaded for the first time, the cache file will be written to your application/cache
folder. On subsequent page loads the cache file will be retrieved and sent to the requesting user’s browser. If it has
expired, it will be deleted and refreshed before being sent to the browser.
Enabling Caching
To enable caching, put the following tag in any of your controller methods:
6.1. General Topics
49
CodeIgniter Documentation, 3.0-dev
$this->output->cache($n);
Where $n is the number of minutes you wish the page to remain cached between refreshes.
The above tag can go anywhere within a method. It is not affected by the order that it appears, so place it wherever it
seems most logical to you. Once the tag is in place, your pages will begin being cached.
: Because of the way CodeIgniter stores content for output, caching will only work if you are generating display for
your controller with a view.
: Before the cache files can be written you must set the file permissions on your application/cache/ directory such
that it is writable.
Deleting Caches
If you no longer wish to cache a file you can remove the caching tag and it will no longer be refreshed when it expires.
: Removing the tag will not delete the cache immediately. It will have to expire normally.
If you need to manually delete the cache, you can use the delete_cache() method:
// Deletes cache for the currently requested URI
$this->output->delete_cache();
// Deletes cache for /foo/bar
$this->output->delete_cache(’/foo/bar’);
6.1.19 Profiling Your Application
The Profiler Class will display benchmark results, queries you have run, and $_POST data at the bottom of your pages.
This information can be useful during development in order to help with debugging and optimization.
Initializing the Class
: This class does NOT need to be initialized. It is loaded automatically by the Output Library if profiling is enabled
as shown below.
Enabling the Profiler
To enable the profiler place the following line anywhere within your Controller methods:
$this->output->enable_profiler(TRUE);
When enabled a report will be generated and inserted at the bottom of your pages.
To disable the profiler you will use:
$this->output->enable_profiler(FALSE);
50
Chapter 6.
CodeIgniter Documentation, 3.0-dev
Setting Benchmark Points
In order for the Profiler to compile and display your benchmark data you must name your mark points using specific
syntax.
Please read the information on setting Benchmark points in the Benchmark Library page.
Enabling and Disabling Profiler Sections
Each section of Profiler data can be enabled or disabled by setting a corresponding config variable to TRUE or FALSE.
This can be done one of two ways. First, you can set application wide defaults with the application/config/profiler.php
config file.
Example:
$config[’config’]
$config[’queries’]
= FALSE;
= FALSE;
In your controllers, you can override the defaults
set_profiler_sections() method of the Output Library:
and
config
file
values
by
calling
the
$sections = array(
’config’ => TRUE,
’queries’ => TRUE
);
$this->output->set_profiler_sections($sections);
Available sections and the array key used to access them are described in the table below.
Key
benchmarks
config
controller_info
get
http_headers
memory_usage
post
queries
uri_string
session_data
query_toggle_count
Description
Elapsed time of Benchmark points and total execution time
CodeIgniter Config variables
The Controller class and method requested
Any GET data passed in the request
The HTTP headers for the current request
Amount of memory consumed by the current request, in bytes
Any POST data passed in the request
Listing of all database queries executed, including execution time
The URI of the current request
Data stored in the current session
The number of queries after which the query block will default to hidden.
Default
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
25
6.1.20 Running via the CLI
As well as calling an applications Controllers via the URL in a browser they can also be loaded via the command-line
interface (CLI).
Page Contents
• Running via the CLI
– What is the CLI?
– Why run via the command-line?
– Let’s try it: Hello World!
– That’s it!
6.1. General Topics
51
CodeIgniter Documentation, 3.0-dev
What is the CLI?
The command-line interface is a text-based method of interacting with computers. For more information, check the
Wikipedia article.
Why run via the command-line?
There are many reasons for running CodeIgniter from the command-line, but they are not always obvious.
• Run your cron-jobs without needing to use wget or curl
• Make your cron-jobs inaccessible from being loaded in the URL by checking the return value of is_cli().
• Make interactive “tasks” that can do things like set permissions, prune cache folders, run backups, etc.
• Integrate with other applications in other languages. For example, a random C++ script could call one command
and run code in your models!
Let’s try it: Hello World!
Let’s create a simple controller so you can see it in action. Using your text editor, create a file called Tools.php, and
put the following code in it:
<?php
class Tools extends CI_Controller {
public function message($to = ’World’)
{
echo "Hello {$to}!".PHP_EOL;
}
}
Then save the file to your application/controllers/ folder.
Now normally you would visit the your site using a URL similar to this:
example.com/index.php/tools/message/to
Instead, we are going to open Terminal in Mac/Linux or go to Run > “cmd” in Windows and navigate to our
CodeIgniter project.
$ cd /path/to/project;
$ php index.php tools message
If you did it right, you should see Hello World! printed.
$ php index.php tools message "John Smith"
Here we are passing it a argument in the same way that URL parameters work. “John Smith” is passed as a argument
and output is:
Hello John Smith!
That’s it!
That, in a nutshell, is all there is to know about controllers on the command line. Remember that this is just a normal
controller, so routing and _remap() works fine.
52
Chapter 6.
CodeIgniter Documentation, 3.0-dev
6.1.21 Managing your Applications
By default it is assumed that you only intend to use CodeIgniter to manage one application, which you will build in
your application/ directory. It is possible, however, to have multiple sets of applications that share a single CodeIgniter
installation, or even to rename or relocate your application directory.
Renaming the Application Directory
If you would like to rename your application directory you may do so as long as you open your main index.php file
and set its name using the $application_folder variable:
$application_folder = ’application’;
Relocating your Application Directory
It is possible to move your application directory to a different location on your server than your web root. To do so
open your main index.php and set a full server path in the $application_folder variable:
$application_folder = ’/path/to/your/application’;
Running Multiple Applications with one CodeIgniter Installation
If you would like to share a common CodeIgniter installation to manage several different applications simply put all
of the directories located inside your application directory into their own sub-directory.
For example, let’s say you want to create two applications, named “foo” and “bar”. You could structure your application directories like this:
applications/foo/
applications/foo/config/
applications/foo/controllers/
applications/foo/errors/
applications/foo/libraries/
applications/foo/models/
applications/foo/views/
applications/bar/
applications/bar/config/
applications/bar/controllers/
applications/bar/errors/
applications/bar/libraries/
applications/bar/models/
applications/bar/views/
To select a particular application for use requires that you open your main index.php file and set the
$application_folder variable. For example, to select the “foo” application for use you would do this:
$application_folder = ’applications/foo’;
: Each of your applications will need its own index.php file which calls the desired application. The index.php file
can be named anything you want.
6.1. General Topics
53
CodeIgniter Documentation, 3.0-dev
6.1.22 Handling Multiple Environments
Developers often desire different system behavior depending on whether an application is running in a development
or production environment. For example, verbose error output is something that would be useful while developing an
application, but it may also pose a security issue when “live”.
The ENVIRONMENT Constant
By default, CodeIgniter comes with the environment constant set to use the value provided in
$_SERVER[’CI_ENV’], otherwise defaults to ‘development’. At the top of index.php, you will see:
define(’ENVIRONMENT’, isset($_SERVER[’CI_ENV’]) ? $_SERVER[’CI_ENV’] : ’development’);
This server variable can be set in your .htaccess file, or Apache config using SetEnv. Alternative methods are available
for nginx and other servers, or you can remove this logic entirely and set the constant based on the HTTP_HOST or
IP.
In addition to affecting some basic framework behavior (see the next section), you may use this constant in your own
development to differentiate between which environment you are running in.
Effects On Default Framework Behavior
There are some places in the CodeIgniter system where the ENVIRONMENT constant is used. This section describes
how default framework behavior is affected.
Error Reporting
Setting the ENVIRONMENT constant to a value of ‘development’ will cause all PHP errors to be rendered to the
browser when they occur. Conversely, setting the constant to ‘production’ will disable all error output. Disabling error
reporting in production is a good security practice.
Configuration Files
Optionally, you can have CodeIgniter load environment-specific configuration files. This may be useful for managing
things like differing API keys across multiple environments. This is described in more detail in the environment
section of the Config Class documentation.
6.1.23 Alternate PHP Syntax for View Files
If you do not utilize CodeIgniter’s template engine, you’ll be using pure PHP in your View files. To minimize the PHP
code in these files, and to make it easier to identify the code blocks it is recommended that you use PHPs alternative
syntax for control structures and short tag echo statements. If you are not familiar with this syntax, it allows you to
eliminate the braces from your code, and eliminate “echo” statements.
Automatic Short Tag Support
: If you find that the syntax described in this page does not work on your server it might be that “short tags” are
disabled in your PHP ini file. CodeIgniter will optionally rewrite short tags on-the-fly, allowing you to use that syntax
even if your server doesn’t support it. This feature can be enabled in your config/config.php file.
54
Chapter 6.
CodeIgniter Documentation, 3.0-dev
Please note that if you do use this feature, if PHP errors are encountered in your view files, the error message and line
number will not be accurately shown. Instead, all errors will be shown as eval() errors.
Alternative Echos
Normally to echo, or print out a variable you would do this:
<?php echo $variable; ?>
With the alternative syntax you can instead do it this way:
<?=$variable?>
Alternative Control Structures
Controls structures, like if, for, foreach, and while can be written in a simplified format as well. Here is an example
using foreach:
<ul>
<?php foreach ($todo as $item): ?>
<li><?=$item?></li>
<?php endforeach; ?>
</ul>
Notice that there are no braces. Instead, the end brace is replaced with endforeach. Each of the control structures
listed above has a similar closing syntax: endif, endfor, endforeach, and endwhile
Also notice that instead of using a semicolon after each structure (except the last one), there is a colon. This is
important!
Here is another example, using if/elseif/else. Notice the colons:
<?php if ($username === ’sally’): ?>
<h3>Hi Sally</h3>
<?php elseif ($username === ’joe’): ?>
<h3>Hi Joe</h3>
<?php else: ?>
<h3>Hi unknown user</h3>
<?php endif; ?>
6.1.24 Security
This page describes some “best practices” regarding web security, and details CodeIgniter’s internal security features.
6.1. General Topics
55
CodeIgniter Documentation, 3.0-dev
URI Security
CodeIgniter is fairly restrictive regarding which characters it allows in your URI strings in order to help minimize the
possibility that malicious data can be passed to your application. URIs may only contain the following:
• Alpha-numeric text (latin characters only)
• Tilde: ~
• Percent sign: %
• Period: .
• Colon: :
• Underscore: _
• Dash: • Space
Register_globals
During system initialization all global variables are unset, except those found in the $_GET, $_POST, and $_COOKIE
arrays. The unsetting routine is effectively the same as register_globals = off.
display_errors
In production environments, it is typically desirable to “disable” PHP’s error reporting by setting the internal display_errors flag to a value of 0. This disables native PHP errors from being rendered as output, which may potentially
contain sensitive information.
Setting CodeIgniter’s ENVIRONMENT constant in index.php to a value of ‘production’ will turn off these errors. In
development mode, it is recommended that a value of ‘development’ is used. More information about differentiating
between environments can be found on the Handling Environments page.
magic_quotes_runtime
The magic_quotes_runtime directive is turned off during system initialization so that you don’t have to remove slashes
when retrieving data from your database.
Best Practices
Before accepting any data into your application, whether it be POST data from a form submission, COOKIE data, URI
data, XML-RPC data, or even data from the SERVER array, you are encouraged to practice this three step approach:
1. Filter the data as if it were tainted.
2. Validate the data to ensure it conforms to the correct type, length, size, etc. (sometimes this step can replace
step one)
3. Escape the data before submitting it into your database.
CodeIgniter provides the following functions to assist in this process:
56
Chapter 6.
CodeIgniter Documentation, 3.0-dev
XSS Filtering
CodeIgniter comes with a Cross Site Scripting filter. This filter looks for commonly used techniques to embed malicious JavaScript into your data, or other types of code that attempt to hijack cookies or do other malicious things. The
XSS Filter is described here.
Validate the data
CodeIgniter has a Form Validation Library that assists you in validating, filtering, and prepping your data.
Escape all data before database insertion
Never insert information into your database without escaping it. Please see the section that discusses database queries
for more information.
Hide your files
Another good security practice is to only leave your index.php and “assets” (e.g. .js, css and image files) under your
server’s webroot directory (most commonly named “htdocs/”). These are the only files that you would need to be
accessible from the web.
Allowing your visitors to see anything else would potentially allow them to access sensitive data, execute scripts, etc.
If you’re not allowed to do that, you can try using a .htaccess file to restrict access to those resources.
CodeIgniter will have an index.html file in all of its directories in an attempt to hide some of this data, but have it in
mind that this is not enough to prevent a serious attacker.
6.1.25 PHP Style Guide
The following page describes the coding styles adhered to when contributing to the development of CodeIgniter. There
is no requirement to use these styles in your own CodeIgniter application, though they are recommended.
6.1. General Topics
57
CodeIgniter Documentation, 3.0-dev
Table of Contents
• PHP Style Guide
– File Format
* TextMate
* BBEdit
– PHP Closing Tag
– File Naming
– Class and Method Naming
– Variable Names
– Commenting
– Constants
– TRUE, FALSE, and NULL
– Logical Operators
– Comparing Return Values and Typecasting
– Debugging Code
– Whitespace in Files
– Compatibility
– One File per Class
– Whitespace
– Line Breaks
– Code Indenting
– Bracket and Parenthetic Spacing
– Localized Text
– Private Methods and Variables
– PHP Errors
– Short Open Tags
– One Statement Per Line
– Strings
– SQL Queries
– Default Function Arguments
File Format
Files should be saved with Unicode (UTF-8) encoding. The BOM should not be used. Unlike UTF-16 and UTF-32,
there’s no byte order to indicate in a UTF-8 encoded file, and the BOM can have a negative side effect in PHP of
sending output, preventing the application from being able to set its own headers. Unix line endings should be used
(LF).
Here is how to apply these settings in some of the more common text editors. Instructions for your text editor may
vary; check your text editor’s documentation.
TextMate
1. Open the Application Preferences
2. Click Advanced, and then the “Saving” tab
3. In “File Encoding”, select “UTF-8 (recommended)”
4. In “Line Endings”, select “LF (recommended)”
5. Optional: Check “Use for existing files as well” if you wish to modify the line endings of files you open to your
new preference.
58
Chapter 6.
CodeIgniter Documentation, 3.0-dev
BBEdit
1. Open the Application Preferences
2. Select “Text Encodings” on the left.
3. In “Default text encoding for new documents”, select “Unicode (UTF-8, no BOM)”
4. Optional: In “If file’s encoding can’t be guessed, use”, select “Unicode (UTF-8, no BOM)”
5. Select “Text Files” on the left.
6. In “Default line breaks”, select “Mac OS X and Unix (LF)”
PHP Closing Tag
The PHP closing tag on a PHP document ?> is optional to the PHP parser. However, if used, any whitespace following
the closing tag, whether introduced by the developer, user, or an FTP application, can cause unwanted output, PHP
errors, or if the latter are suppressed, blank pages. For this reason, all PHP files should OMIT the closing PHP tag,
and instead use a comment block to mark the end of file and its location relative to the application root. This allows
you to still identify a file as being complete and not truncated.
INCORRECT:
<?php
echo "Here’s my code!";
?>
CORRECT:
<?php
echo "Here’s my code!";
/* End of file Myfile.php */
/* Location: ./system/modules/mymodule/myfile.php */
: There should be no empty line or newline character(s) following the closing comments. If you happen to see one
when submitting a pull request, please check your IDE settings and fix it.
File Naming
Class files must be named in a Ucfirst-like manner, while any other file name (configurations, views, generic scripts,
etc.) should be in all lowercase.
INCORRECT:
somelibrary.php
someLibrary.php
SOMELIBRARY.php
Some_Library.php
Application_config.php
Application_Config.php
applicationConfig.php
6.1. General Topics
59
CodeIgniter Documentation, 3.0-dev
CORRECT:
Somelibrary.php
Some_library.php
applicationconfig.php
application_config.php
Furthermore, class file names should match the name of the class itself. For example, if you have a class named
Myclass, then its filename must be Myclass.php.
Class and Method Naming
Class names should always start with an uppercase letter. Multiple words should be separated with an underscore, and
not CamelCased.
INCORRECT:
class superclass
class SuperClass
CORRECT:
class Super_class
class Super_class {
public function __construct()
{
}
}
Class methods should be entirely lowercased and named to clearly indicate their function, preferably including a verb.
Try to avoid overly long and verbose names. Multiple words should be separated with an underscore.
INCORRECT:
function
function
function
function
function
fileproperties()
// not descriptive and needs underscore separator
fileProperties()
// not descriptive and uses CamelCase
getfileproperties()
// Better! But still missing underscore separator
getFileProperties()
// uses CamelCase
get_the_file_properties_from_the_file()
// wordy
CORRECT:
function get_file_properties()
// descriptive, underscore separator, and all lowercase letters
Variable Names
The guidelines for variable naming are very similar to those used for class methods. Variables should contain only
lowercase letters, use underscore separators, and be reasonably named to indicate their purpose and contents. Very
short, non-word variables should only be used as iterators in for() loops.
INCORRECT:
60
Chapter 6.
CodeIgniter Documentation, 3.0-dev
$j = ’foo’;
$Str
$bufferedText
$groupid
$name_of_last_city_used
//
//
//
//
//
single letter variables should only be used in for() loops
contains uppercase letters
uses CamelCasing, and could be shortened without losing semantic meaning
multiple words, needs underscore separator
too long
CORRECT:
for ($j = 0; $j < 10; $j++)
$str
$buffer
$group_id
$last_city
Commenting
In general, code should be commented prolifically. It not only helps describe the flow and intent of the code for less
experienced programmers, but can prove invaluable when returning to your own code months down the line. There is
not a required format for comments, but the following are recommended.
DocBlock style comments preceding class, method, and property declarations so they can be picked up by IDEs:
/**
* Super Class
*
Package Name
* @package
* @subpackage Subpackage
Category
* @category
Author Name
* @author
@link
http://example.com
*
*/
class Super_class {
/**
* Encodes string for use in XML
*
string $str
Input string
* @param
string
* @return
*/
function xml_encode($str)
/**
* Data for class manipulation
*
* @var array
*/
public $data = array();
Use single line comments within code, leaving a blank line between large comment blocks and code.
// break up the string by newlines
$parts = explode("\n", $str);
//
//
//
//
//
A longer comment that needs to give greater detail on what is
occurring and why can use multiple single-line comments. Try to
keep the width reasonable, around 70 characters is the easiest to
read. Don’t hesitate to link to permanent external resources
that may provide greater detail:
6.1. General Topics
61
CodeIgniter Documentation, 3.0-dev
//
// http://example.com/information_about_something/in_particular/
$parts = $this->foo($parts);
Constants
Constants follow the same guidelines as do variables, except constants should always be fully uppercase. Always use
CodeIgniter constants when appropriate, i.e. SLASH, LD, RD, PATH_CACHE, etc.
INCORRECT:
myConstant
// missing underscore separator and not fully uppercase
N
// no single-letter constants
S_C_VER
// not descriptive
$str = str_replace(’{foo}’, ’bar’, $str);
// should use LD and RD constants
CORRECT:
MY_CONSTANT
NEWLINE
SUPER_CLASS_VERSION
$str = str_replace(LD.’foo’.RD, ’bar’, $str);
TRUE, FALSE, and NULL
TRUE, FALSE, and NULL keywords should always be fully uppercase.
INCORRECT:
if ($foo == true)
$bar = false;
function foo($bar = null)
CORRECT:
if ($foo == TRUE)
$bar = FALSE;
function foo($bar = NULL)
Logical Operators
Use of the || “or” comparison operator is discouraged, as its clarity on some output devices is low (looking like the
number 11, for instance). && is preferred over AND but either are acceptable, and a space should always precede and
follow !.
INCORRECT:
if
if
if
if
($foo || $bar)
($foo AND $bar) // okay but not recommended for common syntax highlighting applications
(!$foo)
(! is_array($foo))
CORRECT:
62
Chapter 6.
CodeIgniter Documentation, 3.0-dev
if
if
if
if
($foo OR $bar)
($foo && $bar) // recommended
( ! $foo)
( ! is_array($foo))
Comparing Return Values and Typecasting
Some PHP functions return FALSE on failure, but may also have a valid return value of “” or 0, which would evaluate to FALSE in loose comparisons. Be explicit by comparing the variable type when using these return values in
conditionals to ensure the return value is indeed what you expect, and not a value that has an equivalent loose-type
evaluation.
Use the same stringency in returning and checking your own variables. Use === and !== as necessary.
INCORRECT:
// If ’foo’ is at the beginning of the string, strpos will return a 0,
// resulting in this conditional evaluating as TRUE
if (strpos($str, ’foo’) == FALSE)
CORRECT:
if (strpos($str, ’foo’) === FALSE)
INCORRECT:
function build_string($str = "")
{
if ($str == "") // uh-oh!
{
What if FALSE or the integer 0 is passed as an argument?
}
}
CORRECT:
function build_string($str = "")
{
if ($str === "")
{
}
}
See also information regarding typecasting, which can be quite useful. Typecasting has a slightly different effect
which may be desirable. When casting a variable as a string, for instance, NULL and boolean FALSE variables
become empty strings, 0 (and other numbers) become strings of digits, and boolean TRUE becomes “1”:
$str = (string) $str; // cast $str as a string
Debugging Code
Do not leave debugging code in your submissions, even when commented out. Things such as var_dump(),
print_r(), die()/exit() should not be included in your code unless it serves a specific purpose other than
debugging.
6.1. General Topics
63
CodeIgniter Documentation, 3.0-dev
Whitespace in Files
No whitespace can precede the opening PHP tag or follow the closing PHP tag. Output is buffered, so whitespace
in your files can cause output to begin before CodeIgniter outputs its content, leading to errors and an inability for
CodeIgniter to send proper headers.
Compatibility
CodeIgniter requires a minimum PHP version of 5.2.4. Your code must either be compatible with this minimum requirement, provide a suitable fallback, or be an optional feature that dies quietly without affecting a user’s application.
Additionally, do not use PHP functions that require non-default libraries to be installed unless your code contains an
alternative method when the function is not available.
One File per Class
Use separate files for each class, unless the classes are closely related. An example of a CodeIgniter file that contains
multiple classes is the Xmlrpc library file.
Whitespace
Use tabs for whitespace in your code, not spaces. This may seem like a small thing, but using tabs instead of whitespace
allows the developer looking at your code to have indentation at levels that they prefer and customize in whatever
application they use. And as a side benefit, it results in (slightly) more compact files, storing one tab character versus,
say, four space characters.
Line Breaks
Files must be saved with Unix line breaks. This is more of an issue for developers who work in Windows, but in any
case ensure that your text editor is setup to save files with Unix line breaks.
Code Indenting
Use Allman style indenting. With the exception of Class declarations, braces are always placed on a line by themselves,
and indented at the same level as the control statement that “owns” them.
INCORRECT:
function foo($bar) {
// ...
}
foreach ($arr as $key => $val) {
// ...
}
if ($foo == $bar) {
// ...
} else {
// ...
}
for ($i = 0; $i < 10; $i++)
64
Chapter 6.
CodeIgniter Documentation, 3.0-dev
{
for ($j = 0; $j < 10; $j++)
{
// ...
}
}
try {
// ...
}
catch() {
// ...
}
CORRECT:
function foo($bar)
{
// ...
}
foreach ($arr as $key => $val)
{
// ...
}
if ($foo == $bar)
{
// ...
}
else
{
// ...
}
for ($i = 0; $i < 10; $i++)
{
for ($j = 0; $j < 10; $j++)
{
// ...
}
}
try
{
// ...
}
catch()
{
// ...
}
Bracket and Parenthetic Spacing
In general, parenthesis and brackets should not use any additional spaces. The exception is that a space should always
follow PHP control structures that accept arguments with parenthesis (declare, do-while, elseif, for, foreach, if, switch,
while), to help distinguish them from functions and increase readability.
6.1. General Topics
65
CodeIgniter Documentation, 3.0-dev
INCORRECT:
$arr[ $foo ] = ’foo’;
CORRECT:
$arr[$foo] = ’foo’; // no spaces around array keys
INCORRECT:
function foo ( $bar )
{
}
CORRECT:
function foo($bar) // no spaces around parenthesis in function declarations
{
}
INCORRECT:
foreach( $query->result() as $row )
CORRECT:
foreach ($query->result() as $row) // single space following PHP control structures, but not in inter
Localized Text
CodeIgniter libraries should take advantage of corresponding language files whenever possible.
INCORRECT:
return "Invalid Selection";
CORRECT:
return $this->lang->line(’invalid_selection’);
Private Methods and Variables
Methods and variables that are only accessed internally, such as utility and helper functions that your public methods
use for code abstraction, should be prefixed with an underscore.
public function convert_text()
private function _convert_text()
PHP Errors
Code must run error free and not rely on warnings and notices to be hidden to meet this requirement. For instance,
never access a variable that you did not set yourself (such as $_POST array keys) without first checking to see that it
isset().
Make sure that your dev environment has error reporting enabled for ALL users, and that display_errors is enabled in
the PHP environment. You can check this setting with:
66
Chapter 6.
CodeIgniter Documentation, 3.0-dev
if (ini_get(’display_errors’) == 1)
{
exit "Enabled";
}
On some servers where display_errors is disabled, and you do not have the ability to change this in the php.ini, you
can often enable it with:
ini_set(’display_errors’, 1);
: Setting the display_errors setting with ini_set() at runtime is not identical to having it enabled in the PHP
environment. Namely, it will not have any effect if the script has fatal errors.
Short Open Tags
Always use full PHP opening tags, in case a server does not have short_open_tag enabled.
INCORRECT:
<? echo $foo; ?>
<?=$foo?>
CORRECT:
<?php echo $foo; ?>
: PHP 5.4 will always have the <?= tag available.
One Statement Per Line
Never combine statements on one line.
INCORRECT:
$foo = ’this’; $bar = ’that’; $bat = str_replace($foo, $bar, $bag);
CORRECT:
$foo = ’this’;
$bar = ’that’;
$bat = str_replace($foo, $bar, $bag);
Strings
Always use single quoted strings unless you need variables parsed, and in cases where you do need variables parsed,
use braces to prevent greedy token parsing. You may also use double-quoted strings if the string contains single quotes,
so you do not have to use escape characters.
INCORRECT:
"My String"
"My string $foo"
’SELECT foo FROM bar WHERE baz = \’bag\’’
6.1. General Topics
// no variable parsing, so no use for double quotes
// needs braces
// ugly
67
CodeIgniter Documentation, 3.0-dev
CORRECT:
’My String’
"My string {$foo}"
"SELECT foo FROM bar WHERE baz = ’bag’"
SQL Queries
SQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE, AS, JOIN, ON, IN, etc.
Break up long queries into multiple lines for legibility, preferably breaking for each clause.
INCORRECT:
// keywords are lowercase and query is too long for
// a single line (... indicates continuation of line)
$query = $this->db->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_
...where foo != ’oof’ and baz != ’zab’ order by foobaz limit 5, 100");
CORRECT:
$query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz
FROM exp_pre_email_addresses
WHERE foo != ’oof’
AND baz != ’zab’
ORDER BY foobaz
LIMIT 5, 100");
Default Function Arguments
Whenever appropriate, provide function argument defaults, which helps prevent PHP errors with mistaken calls and
provides common fallback values which can save a few lines of code. Example:
function foo($bar = ’’, $baz = FALSE)
68
Chapter 6.
CHAPTER 7
7.1 Libraries
7.1.1 Benchmarking Class
CodeIgniter has a Benchmarking class that is always active, enabling the time difference between any two marked
points to be calculated.
: This class is initialized automatically by the system so there is no need to do it manually.
In addition, the benchmark is always started the moment the framework is invoked, and ended by the output class
right before sending the final view to the browser, enabling a very accurate timing of the entire system execution to be
shown.
Table of Contents
• Benchmarking Class
– Using the Benchmark Class
– Profiling Your Benchmark Points
– Displaying Total Execution Time
– Displaying Memory Consumption
Using the Benchmark Class
The Benchmark class can be used within your controllers, views, or your models. The process for usage is this:
1. Mark a start point
2. Mark an end point
3. Run the “elapsed time” function to view the results
Here’s an example using real code:
$this->benchmark->mark(’code_start’);
// Some code happens here
$this->benchmark->mark(’code_end’);
69
CodeIgniter Documentation, 3.0-dev
echo $this->benchmark->elapsed_time(’code_start’, ’code_end’);
: The words “code_start” and “code_end” are arbitrary. They are simply words used to set two markers. You can use
any words you want, and you can set multiple sets of markers. Consider this example:
$this->benchmark->mark(’dog’);
// Some code happens here
$this->benchmark->mark(’cat’);
// More code happens here
$this->benchmark->mark(’bird’);
echo $this->benchmark->elapsed_time(’dog’, ’cat’);
echo $this->benchmark->elapsed_time(’cat’, ’bird’);
echo $this->benchmark->elapsed_time(’dog’, ’bird’);
Profiling Your Benchmark Points
If you want your benchmark data to be available to the Profiler all of your marked points must be set up in pairs,
and each mark point name must end with _start and _end. Each pair of points must otherwise be named identically.
Example:
$this->benchmark->mark(’my_mark_start’);
// Some code happens here...
$this->benchmark->mark(’my_mark_end’);
$this->benchmark->mark(’another_mark_start’);
// Some more code happens here...
$this->benchmark->mark(’another_mark_end’);
Please read the Profiler page for more information.
Displaying Total Execution Time
If you would like to display the total elapsed time from the moment CodeIgniter starts to the moment the final output
is sent to the browser, simply place this in one of your view templates:
<?php echo $this->benchmark->elapsed_time();?>
You’ll notice that it’s the same function used in the examples above to calculate the time between two point, except
you are not using any parameters. When the parameters are absent, CodeIgniter does not stop the benchmark until
right before the final output is sent to the browser. It doesn’t matter where you use the function call, the timer will
continue to run until the very end.
An alternate way to show your elapsed time in your view files is to use this pseudo-variable, if you prefer not to use
the pure PHP:
70
Chapter 7.
CodeIgniter Documentation, 3.0-dev
{elapsed_time}
: If you want to benchmark anything within your controller functions you must set your own start/end points.
Displaying Memory Consumption
If your PHP installation is configured with –enable-memory-limit, you can display the amount of memory consumed
by the entire system using the following code in one of your view file:
<?php echo $this->benchmark->memory_usage();?>
: This function can only be used in your view files. The consumption will reflect the total memory used by the entire
app.
An alternate way to show your memory usage in your view files is to use this pseudo-variable, if you prefer not to use
the pure PHP:
{memory_usage}
7.1.2 Caching Driver
CodeIgniter features wrappers around some of the most popular forms of fast and dynamic caching. All but file-based
caching require specific server requirements, and a Fatal Exception will be thrown if server requirements are not met.
Table of Contents
• Caching Driver
– Example Usage
– Function Reference
* is_supported()
* get()
* save()
* delete()
* clean()
* cache_info()
* get_metadata()
– Drivers
* Alternative PHP Cache (APC) Caching
* File-based Caching
* Memcached Caching
* WinCache Caching
* Redis Caching
* Dummy Cache
Example Usage
The following example will load the cache driver, specify APC as the driver to use, and fall back to file-based caching
if APC is not available in the hosting environment.
7.1. Libraries
71
CodeIgniter Documentation, 3.0-dev
$this->load->driver(’cache’, array(’adapter’ => ’apc’, ’backup’ => ’file’));
if ( ! $foo = $this->cache->get(’foo’))
{
echo ’Saving to the cache!<br />’;
$foo = ’foobarbaz!’;
// Save into the cache for 5 minutes
$this->cache->save(’foo’, $foo, 300);
}
echo $foo;
You can also prefix cache item names via the key_prefix setting, which is useful to avoid collisions when you’re
running multiple applications on the same environment.
$this->load->driver(’cache’,
array(’adapter’ => ’apc’, ’backup’ => ’file’, ’key_prefix’ => ’my_’)
);
$this->cache->get(’foo’); // Will get the cache entry named ’my_foo’
Function Reference
class CI_Cache
is_supported()
CI_Cache::is_supported($driver)
This function is automatically called when accessing drivers via $this->cache->get(). However, if
the individual drivers are used, make sure to call this function to ensure the driver is supported in the
hosting environment.
• $driver (string) – the name of the caching driver
TRUE if supported, FALSE if not
Boolean
if ($this->cache->apc->is_supported()
{
if ($data = $this->cache->apc->get(’my_cache’))
{
// do things.
}
}
get()
CI_Cache::get($id)
This function will attempt to fetch an item from the cache store. If the item does not exist, the
function will return FALSE.
72
Chapter 7.
CodeIgniter Documentation, 3.0-dev
• $id (string) – name of cached item
The item if it exists, FALSE if it does not
Mixed
$foo = $this->cache->get(’my_cached_item’);
save()
CI_Cache::save($id, $data[, $ttl ])
This function will save an item to the cache store. If saving fails, the function will return FALSE.
• $id (string) – name of the cached item
• $data (mixed) – the data to save
• $ttl (int) – Time To Live, in seconds (default 60)
TRUE on success, FALSE on failure
Boolean
$this->cache->save(’cache_item_id’, ’data_to_cache’);
delete()
CI_Cache::delete($id)
This function will delete a specific item from the cache store. If item deletion fails, the function will
return FALSE.
• $id (string) – name of cached item
TRUE if deleted, FALSE if the deletion fails
Boolean
$this->cache->delete(’cache_item_id’);
clean()
CI_Cache::clean()
This function will ‘clean’ the entire cache. If the deletion of the cache files fails, the function will
return FALSE.
TRUE if deleted, FALSE if the deletion fails
Boolean
$this->cache->clean();
7.1. Libraries
73
CodeIgniter Documentation, 3.0-dev
cache_info()
CI_Cache::cache_info()
This function will return information on the entire cache.
information on the entire cache
Mixed
var_dump($this->cache->cache_info());
: The information returned and the structure of the data is dependent on which adapter is being
used.
get_metadata()
CI_Cache::get_metadata($id)
This function will return detailed information on a specific item in the cache.
• $id (string) – name of cached item
metadadta for the cached item
Mixed
var_dump($this->cache->get_metadata(’my_cached_item’));
: The information returned and the structure of the data is dependent on which adapter is being
used.
Drivers
Alternative PHP Cache (APC) Caching
All of the functions listed above can be accessed without passing a specific adapter to the driver loader as follows:
$this->load->driver(’cache’);
$this->cache->apc->save(’foo’, ’bar’, 10);
For more information on APC, please see http://php.net/apc.
File-based Caching
Unlike caching from the Output Class, the driver file-based caching allows for pieces of view files to be cached. Use
this with care, and make sure to benchmark your application, as a point can come where disk I/O will negate positive
gains by caching.
All of the functions listed above can be accessed without passing a specific adapter to the driver loader as follows:
$this->load->driver(’cache’);
$this->cache->file->save(’foo’, ’bar’, 10);
74
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Memcached Caching
Multiple Memcached servers can be specified in the memcached.php configuration file, located in the _application/config/* directory.
All of the methods listed above can be accessed without passing a specific adapter to the driver loader as follows:
$this->load->driver(’cache’);
$this->cache->memcached->save(’foo’, ’bar’, 10);
For more information on Memcached, please see http://php.net/memcached.
WinCache Caching
Under Windows, you can also utilize the WinCache driver.
All of the functions listed above can be accessed without passing a specific adapter to the driver loader as follows:
$this->load->driver(’cache’);
$this->cache->wincache->save(’foo’, ’bar’, 10);
For more information on WinCache, please see http://php.net/wincache.
Redis Caching
Redis is an in-memory key-value store which can operate in LRU cache mode. To use it, you need Redis server and
phpredis PHP extension https://github.com/nicolasff/phpredis.
Config options to connect to redis server must be stored in the application/config/redis.php file. Available options are:
$config[’socket_type’] = ’tcp’; //‘tcp‘ or ‘unix‘
$config[’socket’] = ’/var/run/redis.sock’; // in case of ‘unix‘ socket type
$config[’host’] = ’127.0.0.1’;
$config[’password’] = NULL;
$config[’port’] = 6379;
$config[’timeout’] = 0;
All of the methods listed above can be accessed without passing a specific adapter to the driver loader as follows:
$this->load->driver(’cache’);
$this->cache->redis->save(’foo’, ’bar’, 10);
For more information on Redis, please see http://redis.io.
Dummy Cache
This is a caching backend that will always ‘miss.’ It stores no data, but lets you keep your caching code in place in
environments that don’t support your chosen cache.
7.1.3 Calendaring Class
The Calendar class enables you to dynamically create calendars. Your calendars can be formatted through the use of
a calendar template, allowing 100% control over every aspect of its design. In addition, you can pass data to your
calendar cells.
7.1. Libraries
75
CodeIgniter Documentation, 3.0-dev
Initializing the Class
Like most other classes in CodeIgniter, the Calendar class is initialized in your controller using the $this->load->library
function:
$this->load->library(’calendar’);
Once loaded, the Calendar object will be available using:
$this->calendar
Displaying a Calendar
Here is a very simple example showing how you can display a calendar:
$this->load->library(’calendar’);
echo $this->calendar->generate();
The above code will generate a calendar for the current month/year based on your server time. To show a calendar for
a specific month and year you will pass this information to the calendar generating function:
$this->load->library(’calendar’);
echo $this->calendar->generate(2006, 6);
The above code will generate a calendar showing the month of June in 2006. The first parameter specifies the year,
the second parameter specifies the month.
Passing Data to your Calendar Cells
To add data to your calendar cells involves creating an associative array in which the keys correspond to the days
you wish to populate and the array value contains the data. The array is passed to the third parameter of the calendar
generating function. Consider this example:
$this->load->library(’calendar’);
$data = array(
3
7
13
26
);
=>
=>
=>
=>
’http://example.com/news/article/2006/03/’,
’http://example.com/news/article/2006/07/’,
’http://example.com/news/article/2006/13/’,
’http://example.com/news/article/2006/26/’
echo $this->calendar->generate(2006, 6, $data);
Using the above example, day numbers 3, 7, 13, and 26 will become links pointing to the URLs you’ve provided.
: By default it is assumed that your array will contain links. In the section that explains the calendar template
below you’ll see how you can customize how data passed to your cells is handled so you can pass different types of
information.
Setting Display Preferences
There are seven preferences you can set to control various aspects of the calendar. Preferences are set by passing an
array of preferences in the second parameter of the loading function. Here is an example:
76
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$prefs = array (
’start_day’
’month_type’
’day_type’
);
=> ’saturday’,
=> ’long’,
=> ’short’
$this->load->library(’calendar’, $prefs);
echo $this->calendar->generate();
The above code would start the calendar on saturday, use the “long” month heading, and the “short” day names. More
information regarding preferences below.
Preference
template
De- Options
fault
None None
Description
lotime() None
cal_time
start_day sun- Any week day (sunday,
day
monday, tuesday, etc.)
month_typelong long, short
day_type
abr
long, short, abr
show_next_prev
FALSETRUE/FALSE (boolean)
next_prev_url
None A URL
A string containing your calendar template. See the template
section below.
A Unix timestamp corresponding to the current time.
Sets the day of the week the calendar should start on.
Determines what version of the month name to use in the header.
long = January, short = Jan.
Determines what version of the weekday names to use in the
column headers. long = Sunday, short = Sun, abr = Su.
Determines whether to display links allowing you to toggle to
next/previous months. See information on this feature below.
Sets the basepath used in the next/previous calendar links.
Showing Next/Previous Month Links
To allow your calendar to dynamically increment/decrement via the next/previous links requires that you set up your
calendar code similar to this example:
$prefs = array (
’show_next_prev’
’next_prev_url’
);
=> TRUE,
=> ’http://example.com/index.php/calendar/show/’
$this->load->library(’calendar’, $prefs);
echo $this->calendar->generate($this->uri->segment(3), $this->uri->segment(4));
You’ll notice a few things about the above example:
• You must set the “show_next_prev” to TRUE.
• You must supply the URL to the controller containing your calendar in the “next_prev_url” preference.
• You must supply the “year” and “month” to the calendar generating function via the URI segments where they
appear (Note: The calendar class automatically adds the year/month to the base URL you provide.).
Creating a Calendar Template
By creating a calendar template you have 100% control over the design of your calendar. Each component of your
calendar will be placed within a pair of pseudo-variables as shown here:
7.1. Libraries
77
CodeIgniter Documentation, 3.0-dev
$prefs[’template’] = ’
{table_open}<table border="0" cellpadding="0" cellspacing="0">{/table_open}
{heading_row_start}<tr>{/heading_row_start}
{heading_previous_cell}<th><a href="{previous_url}">&lt;&lt;</a></th>{/heading_previous_cell}
{heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell}
{heading_next_cell}<th><a href="{next_url}">&gt;&gt;</a></th>{/heading_next_cell}
{heading_row_end}</tr>{/heading_row_end}
{week_row_start}<tr>{/week_row_start}
{week_day_cell}<td>{week_day}</td>{/week_day_cell}
{week_row_end}</tr>{/week_row_end}
{cal_row_start}<tr>{/cal_row_start}
{cal_cell_start}<td>{/cal_cell_start}
{cal_cell_content}<a href="{content}">{day}</a>{/cal_cell_content}
{cal_cell_content_today}<div class="highlight"><a href="{content}">{day}</a></div>{/cal_cell_conte
{cal_cell_no_content}{day}{/cal_cell_no_content}
{cal_cell_no_content_today}<div class="highlight">{day}</div>{/cal_cell_no_content_today}
{cal_cell_blank}&nbsp;{/cal_cell_blank}
{cal_cell_end}</td>{/cal_cell_end}
{cal_row_end}</tr>{/cal_row_end}
{table_close}</table>{/table_close}
’;
$this->load->library(’calendar’, $prefs);
echo $this->calendar->generate();
7.1.4 Shopping Cart Class
The Cart Class permits items to be added to a session that stays active while a user is browsing your site. These items
can be retrieved and displayed in a standard “shopping cart” format, allowing the user to update the quantity or remove
items from the cart.
Please note that the Cart Class ONLY provides the core “cart” functionality. It does not provide shipping, credit card
authorization, or other processing components.
78
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Page Contents
• Shopping Cart Class
– Initializing the Shopping Cart Class
– Adding an Item to The Cart
– Adding Multiple Items to The Cart
– Displaying the Cart
– Updating The Cart
* What is a Row ID?
– Function Reference
* $this->cart->insert();
* $this->cart->update();
* $this->cart->remove(rowid);
* $this->cart->total();
* $this->cart->total_items();
* $this->cart->contents(boolean);
* $this->cart->get_item($row_id);
* $this->cart->has_options($row_id);
* $this->cart->product_options($row_id);
* $this->cart->destroy();
Initializing the Shopping Cart Class
: The Cart class utilizes CodeIgniter’s Session Class to save the cart information to a database, so before using the
Cart class you must set up a database table as indicated in the Session Documentation, and set the session preferences
in your application/config/config.php file to utilize a database.
To initialize the Shopping Cart Class in your controller constructor, use the $this->load->library function:
$this->load->library(’cart’);
Once loaded, the Cart object will be available using:
$this->cart
: The Cart Class will load and initialize the Session Class automatically, so unless you are using sessions elsewhere
in your application, you do not need to load the Session class.
Adding an Item to The Cart
To add an item to the shopping cart, simply pass an array with the product information to the $this->cart->insert()
function, as shown below:
$data = array(
’id’
’qty’
’price’
’name’
’options’
=>
=>
=>
=>
=>
’sku_123ABC’,
1,
39.95,
’T-Shirt’,
array(’Size’ => ’L’, ’Color’ => ’Red’)
);
$this->cart->insert($data);
7.1. Libraries
79
CodeIgniter Documentation, 3.0-dev
: The first four array indexes above (id, qty, price, and name) are required. If you omit any of them the data will not
be saved to the cart. The fifth index (options) is optional. It is intended to be used in cases where your product has
options associated with it. Use an array for options, as shown above.
The five reserved indexes are:
• id - Each product in your store must have a unique identifier. Typically this will be an “sku” or other such
identifier.
• qty - The quantity being purchased.
• price - The price of the item.
• name - The name of the item.
• options - Any additional attributes that are needed to identify the product. These must be passed via an array.
In addition to the five indexes above, there are two reserved words: rowid and subtotal. These are used internally by
the Cart class, so please do NOT use those words as index names when inserting data into the cart.
Your array may contain additional data. Anything you include in your array will be stored in the session. However, it
is best to standardize your data among all your products in order to make displaying the information in a table easier.
The insert() method will return the $rowid if you successfully insert a single item.
Adding Multiple Items to The Cart
By using a multi-dimensional array, as shown below, it is possible to add multiple products to the cart in one action.
This is useful in cases where you wish to allow people to select from among several items on the same page.
$data = array(
array(
’id’
’qty’
’price’
’name’
’options’
=>
=>
=>
=>
=>
’sku_123ABC’,
1,
39.95,
’T-Shirt’,
array(’Size’ => ’L’, ’Color’ => ’Red’)
’id’
’qty’
’price’
’name’
=>
=>
=>
=>
’sku_567ZYX’,
1,
9.95,
’Coffee Mug’
’id’
’qty’
’price’
’name’
=>
=>
=>
=>
’sku_965QRS’,
1,
29.95,
’Shot Glass’
),
array(
),
array(
)
);
$this->cart->insert($data);
Displaying the Cart
To display the cart you will create a view file with code similar to the one shown below.
80
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Please note that this example uses the form helper.
<?php echo form_open(’path/to/controller/update/function’); ?>
<table cellpadding="6" cellspacing="1" style="width:100%" border="0">
<tr>
<th>QTY</th>
<th>Item Description</th>
<th style="text-align:right">Item Price</th>
<th style="text-align:right">Sub-Total</th>
</tr>
<?php $i = 1; ?>
<?php foreach ($this->cart->contents() as $items): ?>
<?php echo form_hidden($i.’[rowid]’, $items[’rowid’]); ?>
<tr>
<td><?php echo form_input(array(’name’ => $i.’[qty]’, ’value’ => $items[’qty’], ’maxlength’
<td>
<?php echo $items[’name’]; ?>
<?php if ($this->cart->has_options($items[’rowid’]) == TRUE): ?>
<p>
<?php foreach ($this->cart->product_options($items[’rowid’])
<strong><?php echo $option_name; ?>:</strong> <?php e
<?php endforeach; ?>
</p>
<?php endif; ?>
</td>
<td style="text-align:right"><?php echo $this->cart->format_number($items[’price’]); ?></td
<td style="text-align:right">$<?php echo $this->cart->format_number($items[’subtotal’]); ?>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
<tr>
<td colspan="2"> </td>
<td class="right"><strong>Total</strong></td>
<td class="right">$<?php echo $this->cart->format_number($this->cart->total()); ?></td>
</tr>
</table>
<p><?php echo form_submit(’’, ’Update your Cart’); ?></p>
7.1. Libraries
81
CodeIgniter Documentation, 3.0-dev
Updating The Cart
To update the information in your cart, you must pass an array containing the Row ID and quantity to the $this->cart>update() function:
: If the quantity is set to zero, the item will be removed from the cart.
$data = array(
’rowid’ => ’b99ccdf16028f015540f341130b6d8ec’,
’qty’
=> 3
);
$this->cart->update($data);
// Or a multi-dimensional array
$data = array(
array(
’rowid’
’qty’
=> ’b99ccdf16028f015540f341130b6d8ec’,
=> 3
’rowid’
’qty’
=> ’xw82g9q3r495893iajdh473990rikw23’,
=> 4
’rowid’
’qty’
=> ’fh4kdkkkaoe30njgoe92rkdkkobec333’,
=> 2
),
array(
),
array(
)
);
$this->cart->update($data);
What is a Row ID?
The row ID is a unique identifier that is generated by the cart code when an item is added to the cart. The reason a
unique ID is created is so that identical products with different options can be managed by the cart.
For example, let’s say someone buys two identical t-shirts (same product ID), but in different sizes. The product ID
(and other attributes) will be identical for both sizes because it’s the same shirt. The only difference will be the size.
The cart must therefore have a means of identifying this difference so that the two sizes of shirts can be managed
independently. It does so by creating a unique “row ID” based on the product ID and any options associated with it.
In nearly all cases, updating the cart will be something the user does via the “view cart” page, so as a developer, it is
unlikely that you will ever have to concern yourself with the “row ID”, other then making sure your “view cart” page
contains this information in a hidden form field, and making sure it gets passed to the update function when the update
form is submitted. Please examine the construction of the “view cart” page above for more information.
Function Reference
$this->cart->insert();
Permits you to add items to the shopping cart, as outlined above.
82
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->cart->update();
Permits you to update items in the shopping cart, as outlined above.
$this->cart->remove(rowid);
Allows you to remove an item from the shopping cart by passing it the rowid.
$this->cart->total();
Displays the total amount in the cart.
$this->cart->total_items();
Displays the total number of items in the cart.
$this->cart->contents(boolean);
Returns an array containing everything in the cart. You can sort the order, by which this is returned by passing it “true”
where the contents will be sorted from newest to oldest, by leaving this function blank, you’ll automatically just get
first added to the basket to last added to the basket.
$this->cart->get_item($row_id);
Returns an array containing data for the item matching the specified row ID, or FALSE if no such item exists.
$this->cart->has_options($row_id);
Returns TRUE (boolean) if a particular row in the cart contains options. This function is designed to be used in a
loop with $this->cart->contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart
example above.
$this->cart->product_options($row_id);
Returns an array of options for a particular product. This function is designed to be used in a loop with $this->cart>contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above.
$this->cart->destroy();
Permits you to destroy the cart. This function will likely be called when you are finished processing the customer’s
order.
7.1. Libraries
83
CodeIgniter Documentation, 3.0-dev
7.1.5 Config Class
The Config class provides a means to retrieve configuration preferences. These preferences can come from the default
config file (application/config/config.php) or from your own custom config files.
: This class is initialized automatically by the system so there is no need to do it manually.
Page Contents
• Config Class
– Anatomy of a Config File
– Loading a Config File
* Manual Loading
* Auto-loading
– Fetching Config Items
– Setting a Config Item
– Environments
– Helper Functions
* $this->config->site_url();
* $this->config->base_url();
* $this->config->system_url();
Anatomy of a Config File
By default, CodeIgniter has one primary config file, located at application/config/config.php. If you open the file using
your text editor you’ll see that config items are stored in an array called $config.
You can add your own config items to this file, or if you prefer to keep your configuration items separate (assuming
you even need config items), simply create your own file and save it in config folder.
: If you do create your own config files use the same format as the primary one, storing your items in an array called
$config. CodeIgniter will intelligently manage these files so there will be no conflict even though the array has the
same name (assuming an array index is not named the same as another).
Loading a Config File
: CodeIgniter automatically loads the primary config file (application/config/config.php), so you will only need to
load a config file if you have created your own.
There are two ways to load a config file:
Manual Loading
To load one of your custom config files you will use the following function within the controller that needs it:
$this->config->load(’filename’);
Where filename is the name of your config file, without the .php file extension.
84
Chapter 7.
CodeIgniter Documentation, 3.0-dev
If you need to load multiple config files normally they will be merged into one master config array. Name collisions
can occur, however, if you have identically named array indexes in different config files. To avoid collisions you can
set the second parameter to TRUE and each config file will be stored in an array index corresponding to the name of
the config file. Example:
// Stored in an array with this prototype: $this->config[’blog_settings’] = $config
$this->config->load(’blog_settings’, TRUE);
Please see the section entitled Fetching Config Items below to learn how to retrieve config items set this way.
The third parameter allows you to suppress errors in the event that a config file does not exist:
$this->config->load(’blog_settings’, FALSE, TRUE);
Auto-loading
If you find that you need a particular config file globally, you can have it loaded automatically by the system. To do
this, open the autoload.php file, located at application/config/autoload.php, and add your config file as indicated in
the file.
Fetching Config Items
To retrieve an item from your config file, use the following function:
$this->config->item(’item name’);
Where item name is the $config array index you want to retrieve. For example, to fetch your language choice you’ll
do this:
$lang = $this->config->item(’language’);
The function returns NULL if the item you are trying to fetch does not exist.
If you are using the second parameter of the $this->config->load function in order to assign your config items to a
specific index you can retrieve it by specifying the index name in the second parameter of the $this->config->item()
function. Example:
// Loads a config file named blog_settings.php and assigns it to an index named "blog_settings"
$this->config->load(’blog_settings’, TRUE);
// Retrieve a config item named site_name contained within the blog_settings array
$site_name = $this->config->item(’site_name’, ’blog_settings’);
// An alternate way to specify the same item:
$blog_config = $this->config->item(’blog_settings’);
$site_name = $blog_config[’site_name’];
Setting a Config Item
If you would like to dynamically set a config item or change an existing one, you can do so using:
$this->config->set_item(’item_name’, ’item_value’);
Where item_name is the $config array index you want to change, and item_value is its value.
7.1. Libraries
85
CodeIgniter Documentation, 3.0-dev
Environments
You may load different configuration files depending on the current environment. The ENVIRONMENT constant is
defined in index.php, and is described in detail in the Handling Environments section.
To create an environment-specific configuration file, create or copy a configuration file in application/config/{ENVIRONMENT}/{FILENAME}.php
For example, to create a production-only config.php, you would:
1. Create the directory application/config/production/
2. Copy your existing config.php into the above directory
3. Edit application/config/production/config.php so it contains your production settings
When you set the ENVIRONMENT constant to ‘production’, the settings for your new production-only config.php
will be loaded.
You can place the following configuration files in environment-specific folders:
• Default CodeIgniter configuration files
• Your own custom configuration files
: CodeIgniter always loads the global config file first (i.e., the one in application/config/), then tries to load the
configuration files for the current environment. This means you are not obligated to place all of your configuration
files in an environment folder. Only the files that change per environment. Additionally you don’t have to copy all the
config items in the environment config file. Only the config items that you wish to change for your environment. The
config items declared in your environment folders always overwrite those in your global config files.
Helper Functions
The config class has the following helper functions:
$this->config->site_url();
This function retrieves the URL to your site, along with the “index” value you’ve specified in the config file.
$this->config->base_url();
This function retrieves the URL to your site, plus an optional path such as to a stylesheet or image.
The two functions above are normally accessed via the corresponding functions in the URL Helper.
$this->config->system_url();
This function retrieves the URL to your system folder.
7.1.6 Email Class
CodeIgniter’s robust Email Class supports the following features:
• Multiple Protocols: Mail, Sendmail, and SMTP
86
Chapter 7.
CodeIgniter Documentation, 3.0-dev
• TLS and SSL Encryption for SMTP
• Multiple recipients
• CC and BCCs
• HTML or Plaintext email
• Attachments
• Word wrapping
• Priorities
• BCC Batch Mode, enabling large email lists to be broken into small BCC batches.
• Email Debugging tools
Sending Email
Sending email is not only simple, but you can configure it on the fly or set your preferences in a config file.
Here is a basic example demonstrating how you might send email. Note: This example assumes you are sending the
email from one of your controllers.
$this->load->library(’email’);
$this->email->from(’your@example.com’, ’Your Name’);
$this->email->to(’someone@example.com’);
$this->email->cc(’another@another-example.com’);
$this->email->bcc(’them@their-example.com’);
$this->email->subject(’Email Test’);
$this->email->message(’Testing the email class.’);
$this->email->send();
Setting Email Preferences
There are 21 different preferences available to tailor how your email messages are sent. You can either set them
manually as described here, or automatically via preferences stored in your config file, described below:
Preferences are set by passing an array of preference values to the email initialize method. Here is an example of how
you might set some preferences:
$config[’protocol’] = ’sendmail’;
$config[’mailpath’] = ’/usr/sbin/sendmail’;
$config[’charset’] = ’iso-8859-1’;
$config[’wordwrap’] = TRUE;
$this->email->initialize($config);
: Most of the preferences have default values that will be used if you do not set them.
Setting Email Preferences in a Config File
If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create
a new file called the email.php, add the $config array in that file. Then save the file at config/email.php and it will
7.1. Libraries
87
CodeIgniter Documentation, 3.0-dev
be used automatically. You will NOT need to use the $this->email->initialize() method if you save your
preferences in a config file.
Email Preferences
The following is a list of all the preferences that can be set when sending email.
Preference
useragent
protocol
Default
Value
CodeIgniter
wrapchars76
mailtype text
The “user agent”.
None
None
None
None
None
TRUE or
FALSE
(boolean)
tls or ssl
TRUE or
FALSE
(boolean)
text or html
$config[’charset’]
FALSE
TRUE or
FALSE
(boolean)
3
1, 2, 3, 4, 5
\n
new\n
line
bcc_batch_mode
FALSE
bcc_batch_size
200
dsn
FALSE
88
None
mail,
sendmail,
or smtp
/usr/sbin/sendmail
None
smtp_crypto
No Default
wordTRUE
wrap
priority
crlf
Description
mail
mailpath
smtp_hostNo Default
smtp_userNo Default
smtp_passNo Default
smtp_port25
smtp_timeout
5
smtp_keepalive
FALSE
charset
validate
Options
“\r\n” or
“\n” or “\r”
“\r\n” or
“\n” or “\r”
TRUE or
FALSE
(boolean)
None
TRUE or
FALSE
(boolean)
The mail sending protocol.
The server path to Sendmail.
SMTP Server Address.
SMTP Username.
SMTP Password.
SMTP Port.
SMTP Timeout (in seconds).
Enable persistent SMTP connections.
SMTP Encryption
Enable word-wrap.
Character count to wrap at.
Type of mail. If you send HTML email you must send it as a complete
web page. Make sure you don’t have any relative links or relative image
paths otherwise they will not work.
Character set (utf-8, iso-8859-1, etc.).
Whether to validate the email address.
Email Priority. 1 = highest. 5 = lowest. 3 = normal.
Newline character. (Use “\r\n” to comply with RFC 822).
Newline character. (Use “\r\n” to comply with RFC 822).
Enable BCC Batch Mode.
Number of emails in each BCC batch.
Enable notify message from server
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Email Methods Reference
$this->email->from()
Sets the email address and name of the person sending the email:
$this->email->from(’you@example.com’, ’Your Name’);
You can also set a Return-Path, to help redirect undelivered mail:
$this->email->from(’you@example.com’, ’Your Name’, ’returned_emails@example.com’);
: Return-Path can’t be used if you’ve configured ‘smtp’ as your protocol.
$this->email->reply_to()
Sets the reply-to address. If the information is not provided the information in the “from” method is used. Example:
$this->email->reply_to(’you@example.com’, ’Your Name’);
$this->email->to()
Sets the email address(s) of the recipient(s). Can be a single email, a comma-delimited list or an array:
$this->email->to(’someone@example.com’);
$this->email->to(’one@example.com, two@example.com, three@example.com’);
$list = array(’one@example.com’, ’two@example.com’, ’three@example.com’);
$this->email->to($list);
$this->email->cc()
Sets the CC email address(s). Just like the “to”, can be a single email, a comma-delimited list or an array.
$this->email->bcc()
Sets the BCC email address(s). Just like the “to”, can be a single email, a comma-delimited list or an array.
$this->email->subject()
Sets the email subject:
$this->email->subject(’This is my subject’);
7.1. Libraries
89
CodeIgniter Documentation, 3.0-dev
$this->email->message()
Sets the email message body:
$this->email->message(’This is my message’);
$this->email->set_alt_message()
Sets the alternative email message body:
$this->email->set_alt_message(’This is the alternative message’);
This is an optional message string which can be used if you send HTML formatted email. It lets you specify an
alternative message with no HTML formatting which is added to the header string for people who do not accept
HTML email. If you do not set your own message CodeIgniter will extract the message from your HTML email and
strip the tags.
$this->email->set_header()
Appends additional headers to the e-mail:
$this->email->set_header(’Header1’, ’Value1’);
$this->email->set_header(’Header2’, ’Value2’);
$this->email->clear()
Initializes all the email variables to an empty state. This method is intended for use if you run the email sending
method in a loop, permitting the data to be reset between cycles.
foreach ($list as $name => $address)
{
$this->email->clear();
$this->email->to($address);
$this->email->from(’your@example.com’);
$this->email->subject(’Here is your info ’.$name);
$this->email->message(’Hi ’.$name.’ Here is the info you requested.’);
$this->email->send();
}
If you set the parameter to TRUE any attachments will be cleared as well:
$this->email->clear(TRUE);
$this->email->send()
The Email sending method. Returns boolean TRUE or FALSE based on success or failure, enabling it to be used
conditionally:
if ( ! $this->email->send())
{
// Generate error
}
90
Chapter 7.
CodeIgniter Documentation, 3.0-dev
This method will automatically clear all parameters if the request was successful. To stop this behaviour pass FALSE:
if ($this->email->send(FALSE))
{
// Parameters won’t be cleared
}
: In order to use the print_debugger() method, you need to avoid clearing the email parameters.
$this->email->attach()
Enables you to send an attachment. Put the file path/name in the first parameter. Note: Use a file path, not a URL. For
multiple attachments use the method multiple times. For example:
$this->email->attach(’/path/to/photo1.jpg’);
$this->email->attach(’/path/to/photo2.jpg’);
$this->email->attach(’/path/to/photo3.jpg’);
To use the default disposition (attachment), leave the second parameter blank, otherwise use a custom disposition:
$this->email->attach(’image.jpg’, ’inline’);
If you’d like to use a custom file name, you can use the third paramater:
$this->email->attach(’filename.pdf’, ’attachment’, ’report.pdf’);
If you need to use a buffer string instead of a real - physical - file you can use the first parameter as buffer, the third
parameter as file name and the fourth parameter as mime-type:
$this->email->attach($buffer, ’attachment’, ’report.pdf’, ’application/pdf’);
$this->email->print_debugger()
Returns a string containing any server messages, the email headers, and the email messsage. Useful for debugging.
You can optionally specify which parts of the message should be printed. Valid options are: headers, subject, body.
Example:
// You need to pass FALSE while sending in order for the email data
// to not be cleared - if that happens, print_debugger() would have
// nothing to output.
$this->email->send(FALSE);
// Will only print the email headers, excluding the message subject and body
$this->email->print_debugger(array(’headers’));
: By default, all of the raw data will be printed.
Overriding Word Wrapping
If you have word wrapping enabled (recommended to comply with RFC 822) and you have a very long link in your
email it can get wrapped too, causing it to become un-clickable by the person receiving it. CodeIgniter lets you
manually override word wrapping within part of your message like this:
7.1. Libraries
91
CodeIgniter Documentation, 3.0-dev
The text of your email that
gets wrapped normally.
{unwrap}http://example.com/a_long_link_that_should_not_be_wrapped.html{/unwrap}
More text that will be
wrapped normally.
Place the item you do not want word-wrapped between: {unwrap} {/unwrap}
7.1.7 Encryption Class
The Encryption Class provides two-way data encryption. It uses a scheme that either compiles the message using a
randomly hashed bitwise XOR encoding scheme, or is encrypted using the Mcrypt library. If Mcrypt is not available
on your server the encoded message will still provide a reasonable degree of security for encrypted sessions or other
such “light” purposes. If Mcrypt is available, you’ll be provided with a high degree of security appropriate for storage.
Setting your Key
A key is a piece of information that controls the cryptographic process and permits an encrypted string to be decoded.
In fact, the key you chose will provide the only means to decode data that was encrypted with that key, so not only
must you choose the key carefully, you must never change it if you intend use it for persistent data.
It goes without saying that you should guard your key carefully. Should someone gain access to your key, the data will
be easily decoded. If your server is not totally under your control it’s impossible to ensure key security so you may
want to think carefully before using it for anything that requires high security, like storing credit card numbers.
To take maximum advantage of the encryption algorithm, your key should be 32 characters in length (256 bits). The
key should be as random a string as you can concoct, with numbers and uppercase and lowercase letters. Your key
should not be a simple text string. In order to be cryptographically secure it needs to be as random as possible.
Your key can be either stored in your application/config/config.php, or you can design your own storage mechanism
and pass the key dynamically when encoding/decoding.
To save your key to your application/config/config.php, open the file and set:
$config[’encryption_key’] = "YOUR KEY";
Message Length
It’s important for you to know that the encoded messages the encryption function generates will be approximately 2.6
times longer than the original message. For example, if you encrypt the string “my super secret data”, which is 21
characters in length, you’ll end up with an encoded string that is roughly 55 characters (we say “roughly” because the
encoded string length increments in 64 bit clusters, so it’s not exactly linear). Keep this information in mind when
selecting your data storage mechanism. Cookies, for example, can only hold 4K of information.
Initializing the Class
Like most other classes in CodeIgniter, the Encryption class is initialized in your controller using the $this->load>library function:
$this->load->library(’encrypt’);
Once loaded, the Encrypt library object will be available using: $this->encrypt
92
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->encrypt->encode()
Performs the data encryption and returns it as a string. Example:
$msg = ’My secret message’;
$encrypted_string = $this->encrypt->encode($msg);
You can optionally pass your encryption key via the second parameter if you don’t want to use the one in your config
file:
$msg = ’My secret message’;
$key = ’super-secret-key’;
$encrypted_string = $this->encrypt->encode($msg, $key);
$this->encrypt->decode()
Decrypts an encoded string. Example:
$encrypted_string = ’APANtByIGI1BpVXZTJgcsAG8GZl8pdwwa84’;
$plaintext_string = $this->encrypt->decode($encrypted_string);
You can optionally pass your encryption key via the second parameter if you don’t want to use the one in your config
file:
$msg = ’My secret message’;
$key = ’super-secret-key’;
$encrypted_string = $this->encrypt->decode($msg, $key);
$this->encrypt->set_cipher();
Permits you to set an Mcrypt cipher. By default it uses MCRYPT_RIJNDAEL_256. Example:
$this->encrypt->set_cipher(MCRYPT_BLOWFISH);
Please visit php.net for a list of available ciphers.
If you’d like to manually test whether your server supports Mcrypt you can use:
echo ( ! function_exists(’mcrypt_encrypt’)) ? ’Nope’ : ’Yup’;
$this->encrypt->set_mode();
Permits you to set an Mcrypt mode. By default it uses MCRYPT_MODE_CBC. Example:
$this->encrypt->set_mode(MCRYPT_MODE_CFB);
Please visit php.net for a list of available modes.
7.1. Libraries
93
CodeIgniter Documentation, 3.0-dev
$this->encrypt->encode_from_legacy($orig_data, $legacy_mode = MCRYPT_MODE_ECB, $key = ‘’);
Enables you to re-encode data that was originally encrypted with CodeIgniter 1.x to be compatible with the Encryption
library in CodeIgniter 2.x. It is only necessary to use this method if you have encrypted data stored permanently such
as in a file or database and are on a server that supports Mcrypt. “Light” use encryption such as encrypted session data
or transitory encrypted flashdata require no intervention on your part. However, existing encrypted Sessions will be
destroyed since data encrypted prior to 2.x will not be decoded.
: Why only a method to re-encode the data instead of maintaining legacy methods for both encoding and
decoding? The algorithms in the Encryption library have improved in CodeIgniter 2.x both for performance and
security, and we do not wish to encourage continued use of the older methods. You can of course extend the Encryption
library if you wish and replace the new methods with the old and retain seamless compatibility with CodeIgniter 1.x
encrypted data, but this a decision that a developer should make cautiously and deliberately, if at all.
$new_data = $this->encrypt->encode_from_legacy($old_encrypted_string);
PaDefault
Description
rameter
$orig_datan/a
The original encrypted data from CodeIgniter 1.x’s Encryption library
$legacy_mode
MCRYPT_MODE_ECB
The Mcrypt mode that was used to generate the original encrypted data. CodeIgniter
1.x’s default was MCRYPT_MODE_ECB, and it will assume that to be the case unless
overridden by this parameter.
$key
n/a
The encryption key. This it typically specified in your config file as outlined above.
7.1.8 File Uploading Class
CodeIgniter’s File Uploading Class permits files to be uploaded. You can set various preferences, restricting the type
and size of the files.
The Process
Uploading a file involves the following general process:
• An upload form is displayed, allowing a user to select a file and upload it.
• When the form is submitted, the file is uploaded to the destination you specify.
• Along the way, the file is validated to make sure it is allowed to be uploaded based on the preferences you set.
• Once uploaded, the user will be shown a success message.
To demonstrate this process here is brief tutorial. Afterward you’ll find reference information.
Creating the Upload Form
Using a text editor, create a form called upload_form.php. In it, place this code and save it to your application/views/
directory:
<html>
<head>
<title>Upload Form</title>
</head>
<body>
94
Chapter 7.
CodeIgniter Documentation, 3.0-dev
<?php echo $error;?>
<?php echo form_open_multipart(’upload/do_upload’);?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
You’ll notice we are using a form helper to create the opening form tag. File uploads require a multipart form, so the
helper creates the proper syntax for you. You’ll also notice we have an $error variable. This is so we can show error
messages in the event the user does something wrong.
The Success Page
Using a text editor, create a form called upload_success.php. In it, place this code and save it to your application/views/ directory:
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor(’upload’, ’Upload Another File!’); ?></p>
</body>
</html>
The Controller
Using a text editor, create a controller called Upload.php. In it, place this code and save it to your application/controllers/ directory:
<?php
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
7.1. Libraries
95
CodeIgniter Documentation, 3.0-dev
$this->load->helper(array(’form’, ’url’));
}
public function index()
{
$this->load->view(’upload_form’, array(’error’ => ’ ’ ));
}
public function do_upload()
{
$config[’upload_path’]
$config[’allowed_types’]
$config[’max_size’]
$config[’max_width’]
$config[’max_height’]
=
=
=
=
=
’./uploads/’;
’gif|jpg|png’;
100;
1024;
768;
$this->load->library(’upload’, $config);
if ( ! $this->upload->do_upload())
{
$error = array(’error’ => $this->upload->display_errors());
$this->load->view(’upload_form’, $error);
}
else
{
$data = array(’upload_data’ => $this->upload->data());
$this->load->view(’upload_success’, $data);
}
}
}
?>
The Upload Directory
You’ll need a destination directory for your uploaded images. Create a directory at the root of your CodeIgniter
installation called uploads and set its file permissions to 777.
Try it!
To try your form, visit your site using a URL similar to this one:
example.com/index.php/upload/
You should see an upload form. Try uploading an image file (either a jpg, gif, or png). If the path in your controller is
correct it should work.
Reference Guide
Initializing the Upload Class
Like most other classes in CodeIgniter, the Upload class is initialized in your controller using the
$this->load->library() method:
96
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->load->library(’upload’);
Once the Upload class is loaded, the object will be available using: $this->upload
Setting Preferences
Similar to other libraries, you’ll control what is allowed to be upload based on your preferences. In the controller you
built above you set the following preferences:
$config[’upload_path’] = ’./uploads/’;
$config[’allowed_types’] = ’gif|jpg|png’;
$config[’max_size’]
= ’100’;
$config[’max_width’] = ’1024’;
$config[’max_height’] = ’768’;
$this->load->library(’upload’, $config);
// Alternately you can set preferences by calling the ‘‘initialize()‘‘ method. Useful if you auto-loa
$this->upload->initialize($config);
The above preferences should be fairly self-explanatory. Below is a table describing all available preferences.
Preferences
The following preferences are available. The default value indicates what will be used if you do not specify that
preference.
7.1. Libraries
97
CodeIgniter Documentation, 3.0-dev
Preference
Default
Value
None
upload_path
alNone
lowed_types
Options
Description
None
The path to the directory where the upload should be placed. The directory
must be writable and the path can be absolute or relative.
None
The mime types corresponding to the types of files you allow to be
uploaded. Usually the file extension can be used as the mime type.
Separate multiple types with a pipe.
file_name
None
Desired
If set CodeIgniter will rename the uploaded file to this name. The
file name
extension provided in the file name must also be an allowed file type. If no
extension is provided in the original file_name will be used.
file_ext_tolower
FALSE TRUE/FALSEIf set to TRUE, the file extension will be forced to lower case
(boolean)
overwrite
FALSE TRUE/FALSEIf set to true, if a file with the same name as the one you are uploading
(boolean)
exists, it will be overwritten. If set to false, a number will be appended to
the filename if another with the same name exists.
max_size
0
None
The maximum size (in kilobytes) that the file can be. Set to zero for no
limit. Note: Most PHP installations have their own limit, as specified in the
php.ini file. Usually 2 MB (or 2048 KB) by default.
max_width 0
None
The maximum width (in pixels) that the image can be. Set to zero for no
limit.
max_height 0
None
The maximum height (in pixels) that the image can be. Set to zero for no
limit.
min_width 0
None
The minimum width (in pixels) that the image can be. Set to zero for no
limit.
min_height 0
None
The minimum height (in pixels) that the image can be. Set to zero for no
limit.
max_filename0
None
The maximum length that a file name can be. Set to zero for no limit.
max_filename_increment
100
None
When overwrite is set to FALSE, use this to set the maximum filename
increment for CodeIgniter to append to the filename.
enFALSE TRUE/FALSEIf set to TRUE the file name will be converted to a random encrypted
crypt_name
(boolean)
string. This can be useful if you would like the file saved with a name that
can not be discerned by the person uploading it.
reTRUE TRUE/FALSEIf set to TRUE, any spaces in the file name will be converted to
move_spaces
(boolean)
underscores. This is recommended.
deTRUE TRUE/FALSEIf set to TRUE, a server side detection of the file type will be performed to
tect_mime
(boolean)
avoid code injection attacks. DO NOT disable this option unless you have
no other option as that would cause a security risk.
mod_mime_fixTRUE TRUE/FALSEIf set to TRUE, multiple filename extensions will be suffixed with an
(boolean)
underscore in order to avoid triggering Apache mod_mime. DO NOT turn
off this option if your upload directory is public, as this is a security risk.
Setting preferences in a config file
If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create
a new file called the upload.php, add the $config array in that file. Then save the file in: config/upload.php and it
will be used automatically. You will NOT need to use the $this->upload->initialize() method if you save
your preferences in a config file.
Class Reference
The following methods are available:
98
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->upload->do_upload()
Performs the upload based on the preferences you’ve set.
: By default the upload routine expects the file to come from a form field called userfile, and the form must be of type
“multipart”.
<form method="post" action="some_action" enctype="multipart/form-data" />
If you would like to set your own field name simply pass its value to the do_upload() method:
$field_name = "some_field_name";
$this->upload->do_upload($field_name);
$this->upload->display_errors()
Retrieves any error messages if the do_upload() method returned false. The method does not echo automatically,
it returns the data so you can assign it however you need.
Formatting Errors By default the above method wraps any errors within <p> tags. You can set your own delimiters
like this:
$this->upload->display_errors(’<p>’, ’</p>’);
$this->upload->data()
This is a helper method that returns an array containing all of the data related to the file you uploaded. Here is the
array prototype:
Array
(
[file_name]
=> mypic.jpg
[file_type]
=> image/jpeg
[file_path]
=> /path/to/your/upload/
[full_path]
=> /path/to/your/upload/jpg.jpg
[raw_name]
=> mypic
[orig_name]
=> mypic.jpg
[client_name]
=> mypic.jpg
[file_ext]
=> .jpg
[file_size]
=> 22.2
[is_image]
=> 1
[image_width]
=> 800
[image_height] => 600
[image_type]
=> jpeg
[image_size_str] => width="800" height="200"
)
To return one element from the array:
$this->upload->data(’file_name’);
7.1. Libraries
// Returns: mypic.jpg
99
CodeIgniter Documentation, 3.0-dev
Explanation Here is an explanation of the above array items.
Item Description file_name The name of the file that was uploaded including the file extension. file_type The file’s
Mime type file_path The absolute server path to the file full_path The absolute server path including the file name
raw_name The file name without the extension orig_name The original file name. This is only useful if you use
the encrypted name option. client_name The file name as supplied by the client user agent, prior to any file name
preparation or incrementing. file_ext The file extension with period file_size The file size in kilobytes is_image
Whether the file is an image or not. 1 = image. 0 = not. image_width Image width. image_height Image height
image_type Image type. Typically the file extension without the period. image_size_str A string containing the width
and height. Useful to put into an image tag.
7.1.9 Form Validation
CodeIgniter provides a comprehensive form validation and data prepping class that helps minimize the amount of code
you’ll write.
100
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Page Contents
• Form Validation
– Overview
– Form Validation Tutorial
* The Form
* The Success Page
* The Controller
* Try it!
* Explanation
* Setting Validation Rules
* Setting Rules Using an Array
* Cascading Rules
* Prepping Data
* Re-populating the form
* Callbacks: Your own Validation Methods
* Setting Error Messages
* Translating Field Names
* Changing the Error Delimiters
* Showing Errors Individually
* Validating an Array (other than $_POST)
– Saving Sets of Validation Rules to a Config File
* How to save your rules
* Creating Sets of Rules
* Calling a Specific Rule Group
* Associating a Controller Method with a Rule Group
– Using Arrays as Field Names
– Rule Reference
– Prepping Reference
– Class Reference
* $this->form_validation->set_rules()
* $this->form_validation->run()
* $this->form_validation->set_message()
* $this->form_validation->set_data()
* $this->form_validation->reset_validation()
* $this->form_validation->error_array()
– Helper Reference
* form_error()
* validation_errors()
* set_value()
* set_select()
* set_checkbox()
* set_radio()
Overview
Before explaining CodeIgniter’s approach to data validation, let’s describe the ideal scenario:
1. A form is displayed.
2. You fill it in and submit it.
3. If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your
data along with an error message describing the problem.
7.1. Libraries
101
CodeIgniter Documentation, 3.0-dev
4. This process continues until you have submitted a valid form.
On the receiving end, the script must:
1. Check for required data.
2. Verify that the data is of the correct type, and meets the correct criteria. For example, if a username is submitted
it must be validated to contain only permitted characters. It must be of a minimum length, and not exceed a
maximum length. The username can’t be someone else’s existing username, or perhaps even a reserved word.
Etc.
3. Sanitize the data for security.
4. Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.)
5. Prep the data for insertion in the database.
Although there is nothing terribly complex about the above process, it usually requires a significant amount of code,
and to display error messages, various control structures are usually placed within the form HTML. Form validation,
while simple to create, is generally very messy and tedious to implement.
Form Validation Tutorial
What follows is a “hands on” tutorial for implementing CodeIgniters Form Validation.
In order to implement form validation you’ll need three things:
1. A View file containing a form.
2. A View file containing a “success” message to be displayed upon successful submission.
3. A controller method to receive and process the submitted data.
Let’s create those three things, using a member sign-up form as the example.
The Form
Using a text editor, create a form called myform.php. In it, place this code and save it to your application/views/ folder:
<html>
<head>
<title>My Form</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open(’form’); ?>
<h5>Username</h5>
<input type="text" name="username" value="" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="" size="50" />
102
Chapter 7.
CodeIgniter Documentation, 3.0-dev
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
The Success Page
Using a text editor, create a form called formsuccess.php. In it, place this code and save it to your application/views/
folder:
<html>
<head>
<title>My Form</title>
</head>
<body>
<h3>Your form was successfully submitted!</h3>
<p><?php echo anchor(’form’, ’Try it again!’); ?></p>
</body>
</html>
The Controller
Using a text editor, create a controller called form.php. In it, place this code and save it to your application/controllers/
folder:
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array(’form’, ’url’));
$this->load->library(’form_validation’);
if ($this->form_validation->run() == FALSE)
{
$this->load->view(’myform’);
}
else
{
$this->load->view(’formsuccess’);
}
}
}
Try it!
To try your form, visit your site using a URL similar to this one:
7.1. Libraries
103
CodeIgniter Documentation, 3.0-dev
example.com/index.php/form/
If you submit the form you should simply see the form reload. That’s because you haven’t set up any validation rules
yet.
Since you haven’t told the Form Validation class to validate anything yet, it returns FALSE (boolean false) by
default. ‘‘The run()‘‘ method only returns TRUE if it has successfully applied your rules without any of them
failing.
Explanation
You’ll notice several things about the above pages:
The form (myform.php) is a standard web form with a couple exceptions:
1. It uses a form helper to create the form opening. Technically, this isn’t necessary. You could create the form
using standard HTML. However, the benefit of using the helper is that it generates the action URL for you, based
on the URL in your config file. This makes your application more portable in the event your URLs change.
2. At the top of the form you’ll notice the following function call:
<?php echo validation_errors(); ?>
This function will return any error messages sent back by the validator. If there are no messages it returns an
empty string.
The controller (form.php) has one method: index(). This method initializes the validation class and loads the form
helper and URL helper used by your view files. It also runs the validation routine. Based on whether the validation
was successful it either presents the form or the success page.
Setting Validation Rules
CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even
lets you prep and pre-process the field data at the same time. To set validation rules you will use the set_rules()
method:
$this->form_validation->set_rules();
The above method takes three parameters as input:
1. The field name - the exact name you’ve given the form field.
2. A “human” name for this field, which will be inserted into the error message. For example, if your field is named
“user” you might give it a human name of “Username”.
3. The validation rules for this form field.
: If you would like the field name to be stored in a language file, please see Translating Field Names.
Here is an example. In your controller (form.php), add this code just below the validation initialization method:
$this->form_validation->set_rules(’username’, ’Username’, ’required’);
$this->form_validation->set_rules(’password’, ’Password’, ’required’);
$this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’required’);
$this->form_validation->set_rules(’email’, ’Email’, ’required’);
Your controller should now look like this:
104
Chapter 7.
CodeIgniter Documentation, 3.0-dev
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array(’form’, ’url’));
$this->load->library(’form_validation’);
$this->form_validation->set_rules(’username’, ’Username’, ’required’);
$this->form_validation->set_rules(’password’, ’Password’, ’required’);
$this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’required’);
$this->form_validation->set_rules(’email’, ’Email’, ’required’);
if ($this->form_validation->run() == FALSE)
{
$this->load->view(’myform’);
}
else
{
$this->load->view(’formsuccess’);
}
}
}
Now submit the form with the fields blank and you should see the error messages. If you submit the form with all the
fields populated you’ll see your success page.
: The form fields are not yet being re-populated with the data when there is an error. We’ll get to that shortly.
Setting Rules Using an Array
Before moving on it should be noted that the rule setting method can be passed an array if you prefer to set all your
rules in one action. If you use this approach, you must name your array keys as indicated:
$config = array(
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
7.1. Libraries
=> ’username’,
=> ’Username’,
=> ’required’
=> ’password’,
=> ’Password’,
=> ’required’
=> ’passconf’,
=> ’Password Confirmation’,
=> ’required’
=> ’email’,
=> ’Email’,
=> ’required’
105
CodeIgniter Documentation, 3.0-dev
)
);
$this->form_validation->set_rules($config);
Cascading Rules
CodeIgniter lets you pipe multiple rules together. Let’s try it. Change your rules in the third parameter of rule setting
method, like this:
$this->form_validation->set_rules(’username’, ’Username’, ’required|min_length[5]|max_length[12]|is_u
$this->form_validation->set_rules(’password’, ’Password’, ’required’);
$this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’required|matches[password]’);
$this->form_validation->set_rules(’email’, ’Email’, ’required|valid_email|is_unique[users.email]’);
The above code sets the following rules:
1. The username field be no shorter than 5 characters and no longer than 12.
2. The password field must match the password confirmation field.
3. The email field must contain a valid email address.
Give it a try! Submit your form without the proper data and you’ll see new error messages that correspond to your
new rules. There are numerous rules available which you can read about in the validation reference.
: You can also pass an array of rules to set_rules(), instead of a string. Example:
$this->form_validation->set_rules(’username’, ’Username’, array(’required’, ’min_length[5]’));
Prepping Data
In addition to the validation method like the ones we used above, you can also prep your data in various ways. For
example, you can set up rules like this:
$this->form_validation->set_rules(’username’, ’Username’, ’trim|required|min_length[5]|max_length[12]
$this->form_validation->set_rules(’password’, ’Password’, ’trim|required|md5’);
$this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’trim|required|matches[passwor
$this->form_validation->set_rules(’email’, ’Email’, ’trim|required|valid_email’);
In the above example, we are “trimming” the fields, converting the password to MD5, and running the username
through the xss_clean() method, which removes malicious data.
Any native PHP function that accepts one parameter can be used as a rule, like htmlspecialchars, trim, md5,
etc.
: You will generally want to use the prepping functions after the validation rules so if there is an error, the original
data will be shown in the form.
Re-populating the form
Thus far we have only been dealing with errors. It’s time to repopulate the form field with the submitted data.
CodeIgniter offers several helper functions that permit you to do this. The one you will use most commonly is:
106
Chapter 7.
CodeIgniter Documentation, 3.0-dev
set_value(’field name’)
Open your myform.php view file and update the value in each field using the set_value() function:
Don’t forget to include each field name in the ‘‘set_value()‘‘ functions!
<html>
<head>
<title>My Form</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open(’form’); ?>
<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value(’username’); ?>" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value(’password’); ?>" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value(’passconf’); ?>" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value(’email’); ?>" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
Now reload your page and submit the form so that it triggers an error. Your form fields should now be re-populated
: The Class Reference section below contains functions that permit you to re-populate <select> menus, radio buttons,
and checkboxes.
Important Note: If you use an array as the name of a form field, you must supply it as an array to the function.
Example:
<input type="text" name="colors[]" value="<?php echo set_value(’colors[]’); ?>" size="50" />
For more info please see the Using Arrays as Field Names section below.
Callbacks: Your own Validation Methods
The validation system supports callbacks to your own validation methods. This permits you to extend the validation
class to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique
username, you can create a callback method that does that. Let’s create an example of this.
In your controller, change the “username” rule to this:
$this->form_validation->set_rules(’username’, ’Username’, ’callback_username_check’);
7.1. Libraries
107
CodeIgniter Documentation, 3.0-dev
Then add a new method called username_check() to your controller. Here’s how your controller should now
look:
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array(’form’, ’url’));
$this->load->library(’form_validation’);
$this->form_validation->set_rules(’username’, ’Username’, ’callback_username_check’);
$this->form_validation->set_rules(’password’, ’Password’, ’required’);
$this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’required’);
$this->form_validation->set_rules(’email’, ’Email’, ’required|is_unique[users.email]’
if ($this->form_validation->run() == FALSE)
{
$this->load->view(’myform’);
}
else
{
$this->load->view(’formsuccess’);
}
}
public function username_check($str)
{
if ($str == ’test’)
{
$this->form_validation->set_message(’username_check’, ’The {field} field can
return FALSE;
}
else
{
return TRUE;
}
}
}
Reload your form and submit it with the word “test” as the username. You can see that the form field data was passed
to your callback method for you to process.
To invoke a callback just put the method name in a rule, with “callback_” as the rule prefix. If you need to receive an
extra parameter in your callback method, just add it normally after the method name between square brackets, as in:
“callback_foo**[bar]**”, then it will be passed as the second argument of your callback method.
: You can also process the form data that is passed to your callback and return it. If your callback returns anything
other than a boolean TRUE/FALSE it is assumed that the data is your newly processed form data.
Setting Error Messages
All of the native error messages are
tem/language/english/form_validation_lang.php
108
located
in
the
following
language
file:
sys-
Chapter 7.
CodeIgniter Documentation, 3.0-dev
To set your own custom message you can either edit that file, or use the following method:
$this->form_validation->set_message(’rule’, ’Error Message’);
Where rule corresponds to the name of a particular rule, and Error Message is the text you would like displayed.
If you’d like to include a field’s “human” name, or the optional parameter some rules allow for (such as max_length),
you can add the {field} and {param} tags to your message, respectively:
$this->form_validation->set_message(’min_length’, ’{field} must have at least {param} characters.’);
On a field with the human name Username and a rule of min_length[5], an error would display: “Username must have
at least 5 characters.”
: The old sprintf() method of using %s in your error messages will still work, however it will override the tags above.
You should use one or the other.
In the callback rule example above, the error message was set by passing the name of the method (without the “callback_” prefix):
$this->form_validation->set_message(’username_check’)
Translating Field Names
If you would like to store the “human” name you passed to the set_rules() method in a language file, and therefore
make the name able to be translated, here’s how:
First, prefix your “human” name with lang:, as in this example:
$this->form_validation->set_rules(’first_name’, ’lang:first_name’, ’required’);
Then, store the name in one of your language file arrays (without the prefix):
$lang[’first_name’] = ’First Name’;
: If you store your array item in a language file that is not loaded automatically by CI, you’ll need to remember to
load it in your controller using:
$this->lang->load(’file_name’);
See the Language Class page for more info regarding language files.
Changing the Error Delimiters
By default, the Form Validation class adds a paragraph tag (<p>) around each error message shown. You can either
change these delimiters globally, individually, or change the defaults in a config file.
1. Changing delimiters Globally To globally change the error delimiters, in your controller method, just after
loading the Form Validation class, add this:
$this->form_validation->set_error_delimiters(’<div class="error">’, ’</div>’);
In this example, we’ve switched to using div tags.
2. Changing delimiters Individually Each of the two error generating functions shown in this tutorial can be
supplied their own delimiters as follows:
7.1. Libraries
109
CodeIgniter Documentation, 3.0-dev
<?php echo form_error(’field name’, ’<div class="error">’, ’</div>’); ?>
Or:
<?php echo validation_errors(’<div class="error">’, ’</div>’); ?>
3. Set delimiters in a config file You can add your error delimiters in application/config/form_validation.php as
follows:
$config[’error_prefix’] = ’<div class="error_prefix">’;
$config[’error_suffix’] = ’</div>’;
Showing Errors Individually
If you prefer to show an error message next to each form field, rather than as a list, you can use the form_error()
function.
Try it! Change your form so that it looks like this:
<h5>Username</h5>
<?php echo form_error(’username’); ?>
<input type="text" name="username" value="<?php echo set_value(’username’); ?>" size="50" />
<h5>Password</h5>
<?php echo form_error(’password’); ?>
<input type="text" name="password" value="<?php echo set_value(’password’); ?>" size="50" />
<h5>Password Confirm</h5>
<?php echo form_error(’passconf’); ?>
<input type="text" name="passconf" value="<?php echo set_value(’passconf’); ?>" size="50" />
<h5>Email Address</h5>
<?php echo form_error(’email’); ?>
<input type="text" name="email" value="<?php echo set_value(’email’); ?>" size="50" />
If there are no errors, nothing will be shown. If there is an error, the message will appear.
: If you use an array as the name of a form field, you must supply it as an array to the function. Example:
<?php echo form_error(’options[size]’); ?>
<input type="text" name="options[size]" value="<?php echo set_value("options[size]"); ?>" size="50" /
For more info please see the Using Arrays as Field Names section below.
Validating an Array (other than $_POST)
Sometimes you may want to validate an array that does not originate from $_POST data.
In this case, you can specify the array to be validated:
$data = array(
’username’ => ’johndoe’,
’password’ => ’mypassword’,
’passconf’ => ’mypassword’
);
110
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->form_validation->set_data($data);
Creating validation rules, running the validation, and retrieving error messages works the same whether you are validating $_POST data or an array.
:
If you want to validate more than one array during a single execution, then you should call the
reset_validation() method before setting up rules and validating the new array.
For more info please see the Class Reference section below.
Saving Sets of Validation Rules to a Config File
A nice feature of the Form Validation class is that it permits you to store all your validation rules for your entire application in a config file. You can organize these rules into “groups”. These groups can either be loaded automatically
when a matching controller/method is called, or you can manually call each set as needed.
How to save your rules
To store your validation rules, simply create a file named form_validation.php in your application/config/ folder. In
that file you will place an array named $config with your rules. As shown earlier, the validation array will have this
prototype:
$config = array(
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
)
);
=> ’username’,
=> ’Username’,
=> ’required’
=> ’password’,
=> ’Password’,
=> ’required’
=> ’passconf’,
=> ’Password Confirmation’,
=> ’required’
=> ’email’,
=> ’Email’,
=> ’required’
Your validation rule file will be loaded automatically and used when you call the run() method.
Please note that you MUST name your $config array.
Creating Sets of Rules
In order to organize your rules into “sets” requires that you place them into “sub arrays”. Consider the following
example, showing two sets of rules. We’ve arbitrarily called these two rules “signup” and “email”. You can name your
rules anything you want:
7.1. Libraries
111
CodeIgniter Documentation, 3.0-dev
$config = array(
’signup’ => array(
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
)
),
’email’ => array(
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
)
)
);
=> ’username’,
=> ’Username’,
=> ’required’
=> ’password’,
=> ’Password’,
=> ’required’
=> ’passconf’,
=> ’Password Confirmation’,
=> ’required’
=> ’email’,
=> ’Email’,
=> ’required’
=> ’emailaddress’,
=> ’EmailAddress’,
=> ’required|valid_email’
=> ’name’,
=> ’Name’,
=> ’required|alpha’
=> ’title’,
=> ’Title’,
=> ’required’
=> ’message’,
=> ’MessageBody’,
=> ’required’
Calling a Specific Rule Group
In order to call a specific group, you will pass its name to the run() method. For example, to call the signup rule you
will do this:
if ($this->form_validation->run(’signup’) == FALSE)
{
$this->load->view(’myform’);
}
else
112
Chapter 7.
CodeIgniter Documentation, 3.0-dev
{
$this->load->view(’formsuccess’);
}
Associating a Controller Method with a Rule Group
An alternate (and more automatic) method of calling a rule group is to name it according to the controller class/method
you intend to use it with. For example, let’s say you have a controller named Member and a method named signup.
Here’s what your class might look like:
<?php
class Member extends CI_Controller {
public function signup()
{
$this->load->library(’form_validation’);
if ($this->form_validation->run() == FALSE)
{
$this->load->view(’myform’);
}
else
{
$this->load->view(’formsuccess’);
}
}
}
In your validation config file, you will name your rule group member/signup:
$config = array(
’member/signup’ => array(
array(
’field’ =>
’label’ =>
’rules’ =>
),
array(
’field’ =>
’label’ =>
’rules’ =>
),
array(
’field’ =>
’label’ =>
’rules’ =>
),
array(
’field’ =>
’label’ =>
’rules’ =>
)
)
);
’username’,
’Username’,
’required’
’password’,
’Password’,
’required’
’passconf’,
’PasswordConfirmation’,
’required’
’email’,
’Email’,
’required’
When a rule group is named identically to a controller class/method it will be used automatically when the run()
7.1. Libraries
113
CodeIgniter Documentation, 3.0-dev
method is invoked from that class/method.
Using Arrays as Field Names
The Form Validation class supports the use of arrays as field names. Consider this example:
<input type="text" name="options[]" value="" size="50" />
If you do use an array as a field name, you must use the EXACT array name in the Helper Functions that require the
field name, and as your Validation Rule field name.
For example, to set a rule for the above field you would use:
$this->form_validation->set_rules(’options[]’, ’Options’, ’required’);
Or, to show an error for the above field you would use:
<?php echo form_error(’options[]’); ?>
Or to re-populate the field you would use:
<input type="text" name="options[]" value="<?php echo set_value(’options[]’); ?>" size="50" />
You can use multidimensional arrays as field names as well. For example:
<input type="text" name="options[size]" value="" size="50" />
Or even:
<input type="text" name="sports[nba][basketball]" value="" size="50" />
As with our first example, you must use the exact array name in the helper functions:
<?php echo form_error(’sports[nba][basketball]’); ?>
If you are using checkboxes (or other fields) that have multiple options, don’t forget to leave an empty bracket after
each option, so that all selections will be added to the POST array:
<input type="checkbox" name="options[]" value="red" />
<input type="checkbox" name="options[]" value="blue" />
<input type="checkbox" name="options[]" value="green" />
Or if you use a multidimensional array:
<input type="checkbox" name="options[color][]" value="red" />
<input type="checkbox" name="options[color][]" value="blue" />
<input type="checkbox" name="options[color][]" value="green" />
When you use a helper function you’ll include the bracket as well:
<?php echo form_error(’options[color][]’); ?>
Rule Reference
The following is a list of all the native rules that are available to use:
114
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Rule
required
matches
differs
Parameter
No
Yes
Yes
is_unique
Yes
min_length Yes
max_length Yes
exYes
act_length
greater_than Yes
Description
Returns FALSE if the form element is empty.
Returns FALSE if the form element does not match the one in the parameter.
Returns FALSE if the form element does not differ from the one in the
parameter.
Returns FALSE if the form element is not unique to the table and field name
in the parameter. Note: This rule requires Query Builder to be enabled in
order to work.
Returns FALSE if the form element is shorter then the parameter value.
Returns FALSE if the form element is longer then the parameter value.
Returns FALSE if the form element is not exactly the parameter value.
Returns FALSE if the form element is less than or equal to the parameter
value or not numeric.
greater_than_equal_to
Yes
Returns FALSE if the form element is less than the parameter value, or not
numeric.
less_than
Yes
Returns FALSE if the form element is greater than or equal to the parameter
value or not numeric.
less_than_equal_to
Yes
Returns FALSE if the form element is greater than the parameter value, or
not numeric.
alpha
No
Returns FALSE if the form element contains anything other than
alphabetical characters.
alNo
Returns FALSE if the form element contains anything other than
pha_numeric
alpha-numeric characters.
alNo
Returns FALSE if the form element contains anything other than
pha_numeric_spaces alpha-numeric characters or spaces. Should be used after trim to avoid
spaces at the beginning or end.
alNo
Returns FALSE if the form element contains anything other than
pha_dash
alpha-numeric characters, underscores or dashes.
numeric
No
Returns FALSE if the form element contains anything other than numeric
characters.
integer
No
Returns FALSE if the form element contains anything other than an integer.
decimal
No
Returns FALSE if the form element contains anything other than a decimal
number.
is_natural No
Returns FALSE if the form element contains anything other than a natural
number: 0, 1, 2, 3, etc.
is_natural_no_zero
No
Returns FALSE if the form element contains anything other than a natural
number, but not zero: 1, 2, 3, etc.
valid_url
No
Returns FALSE if the form element does not contain a valid URL.
valid_email No
Returns FALSE if the form element does not contain a valid email address.
valid_emails No
Returns FALSE if any value provided in a comma separated list is not a
valid email.
valid_ip
No
Returns FALSE if the supplied IP is not valid. Accepts an optional
parameter of ‘ipv4’ or ‘ipv6’ to specify an IP format.
valid_base64 No
Returns FALSE if the supplied string contains anything other than valid
Base64 characters.
Example
matches[form_item]
differs[form_item]
is_unique[table.field]
min_length[3]
max_length[12]
exact_length[8]
greater_than[8]
greater_than_equal_to[8]
less_than[8]
less_than_equal_to[8]
: These rules can also be called as discrete methods. For example:
$this->form_validation->required($string);
: You can also use any native PHP functions that permit up to two parameters, where at least one is required (to pass
7.1. Libraries
115
CodeIgniter Documentation, 3.0-dev
the field data).
Prepping Reference
The following is a list of all the prepping methods that are available to use:
Name
xss_clean
Parameter
No
prep_for_form
No
prep_url
No
strip_image_tags No
enNo
code_php_tags
Description
Runs the data through the XSS filtering method, described in the Security Class
page.
Converts special characters so that HTML data can be shown in a form field
without breaking it.
Adds “http://” to URLs if missing.
Strips the HTML from image tags leaving the raw URL.
Converts PHP tags to entities.
: You can also use any native PHP functions that permits one parameter, like trim(), htmlspecialchars(),
urldecode(), etc.
Class Reference
class Form_validation
The following methods are intended for use in your controller.
$this->form_validation->set_rules()
Form_validation::set_rules($field, $label = ‘’, $rules = ‘’)
• $field (string) – The field name
• $label (string) – The field label
• $rules (mixed) – The rules, as a string with rules separated by a pipe “|”, or an array
or rules.
Object
Permits you to set validation rules, as described in the tutorial sections above:
• Setting Validation Rules
• Saving Sets of Validation Rules to a Config File
$this->form_validation->run()
Form_validation::run($group = ‘’)
• $group (string) – The name of the validation group to run
Boolean
116
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Runs the validation routines. Returns boolean TRUE on success and FALSE on failure. You can
optionally pass the name of the validation group via the method, as described in: Saving Sets of
Validation Rules to a Config File
$this->form_validation->set_message()
Form_validation::set_message($lang, $val = ‘’)
• $lang (string) – The rule the message is for
• $val (string) – The message
Object
Permits you to set custom error messages. See Setting Error Messages
$this->form_validation->set_data()
Form_validation::set_data($data = ‘’)
• $data (array) – The data to validate
Permits you to set an array for validation, instead of using the default $_POST array.
$this->form_validation->reset_validation()
Form_validation::reset_validation()
Permits you to reset the validation when you validate more than one array. This method should be
called before validating each new array.
$this->form_validation->error_array()
Form_validation::error_array()
Array
Returns the error messages as an array.
Helper Reference
The following helper functions are available for use in the view files containing your forms. Note that these are
procedural functions, so they do not require you to prepend them with $this->form_validation.
form_error()
Shows an individual error message associated with the field name supplied to the function. Example:
<?php echo form_error(’username’); ?>
The error delimiters can be optionally specified. See the Changing the Error Delimiters section above.
7.1. Libraries
117
CodeIgniter Documentation, 3.0-dev
validation_errors()
Shows all error messages as a string: Example:
<?php echo validation_errors(); ?>
The error delimiters can be optionally specified. See the Changing the Error Delimiters section above.
set_value()
Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the
function. The second (optional) parameter allows you to set a default value for the form. Example:
<input type="text" name="quantity" value="<?php echo set_value(’quantity’, ’0’); ?>" size="50" />
The above form will show “0” when loaded for the first time.
set_select()
If you use a <select> menu, this function permits you to display the menu item that was selected. The first parameter
must contain the name of the select menu, the second parameter must contain the value of each item, and the third
(optional) parameter lets you set an item as the default (use boolean TRUE/FALSE).
Example:
<select name="myselect">
<option value="one" <?php echo set_select(’myselect’, ’one’, TRUE); ?> >One</option>
<option value="two" <?php echo set_select(’myselect’, ’two’); ?> >Two</option>
<option value="three" <?php echo set_select(’myselect’, ’three’); ?> >Three</option>
</select>
set_checkbox()
Permits you to display a checkbox in the state it was submitted. The first parameter must contain the name of the
checkbox, the second parameter must contain its value, and the third (optional) parameter lets you set an item as the
default (use boolean TRUE/FALSE). Example:
<input type="checkbox" name="mycheck[]" value="1" <?php echo set_checkbox(’mycheck[]’, ’1’); ?> />
<input type="checkbox" name="mycheck[]" value="2" <?php echo set_checkbox(’mycheck[]’, ’2’); ?> />
set_radio()
Permits you to display radio buttons in the state they were submitted. This function is identical to the set_checkbox()
function above.
<input type="radio" name="myradio" value="1" <?php echo set_radio(’myradio’, ’1’, TRUE); ?> />
<input type="radio" name="myradio" value="2" <?php echo set_radio(’myradio’, ’2’); ?> />
118
Chapter 7.
CodeIgniter Documentation, 3.0-dev
7.1.10 FTP Class
CodeIgniter’s FTP Class permits files to be transfered to a remote server. Remote files can also be moved, renamed,
and deleted. The FTP class also includes a “mirroring” function that permits an entire local directory to be recreated
remotely via FTP.
: SFTP and SSL FTP protocols are not supported, only standard FTP.
Initializing the Class
Like most other classes in CodeIgniter, the FTP class is initialized in your controller using the $this->load->library
function:
$this->load->library(’ftp’);
Once loaded, the FTP object will be available using: $this->ftp
Usage Examples
In this example a connection is opened to the FTP server, and a local file is read and uploaded in ASCII mode. The
file permissions are set to 755.
$this->load->library(’ftp’);
$config[’hostname’] = ’ftp.example.com’;
$config[’username’] = ’your-username’;
$config[’password’] = ’your-password’;
$config[’debug’]
= TRUE;
$this->ftp->connect($config);
$this->ftp->upload(’/local/path/to/myfile.html’, ’/public_html/myfile.html’, ’ascii’, 0775);
$this->ftp->close();
In this example a list of files is retrieved from the server.
$this->load->library(’ftp’);
$config[’hostname’] = ’ftp.example.com’;
$config[’username’] = ’your-username’;
$config[’password’] = ’your-password’;
$config[’debug’]
= TRUE;
$this->ftp->connect($config);
$list = $this->ftp->list_files(’/public_html/’);
print_r($list);
$this->ftp->close();
In this example a local directory is mirrored on the server.
7.1. Libraries
119
CodeIgniter Documentation, 3.0-dev
$this->load->library(’ftp’);
$config[’hostname’] = ’ftp.example.com’;
$config[’username’] = ’your-username’;
$config[’password’] = ’your-password’;
$config[’debug’]
= TRUE;
$this->ftp->connect($config);
$this->ftp->mirror(’/path/to/myfolder/’, ’/public_html/myfolder/’);
$this->ftp->close();
Function Reference
$this->ftp->connect()
Connects and logs into to the FTP server. Connection preferences are set by passing an array to the function, or you
can store them in a config file.
Here is an example showing how you set preferences manually:
$this->load->library(’ftp’);
$config[’hostname’]
$config[’username’]
$config[’password’]
$config[’port’]
$config[’passive’]
$config[’debug’]
=
=
=
=
=
=
’ftp.example.com’;
’your-username’;
’your-password’;
21;
FALSE;
TRUE;
$this->ftp->connect($config);
Setting FTP Preferences in a Config File If you prefer you can store your FTP preferences in a config file. Simply
create a new file called the ftp.php, add the $config array in that file. Then save the file at config/ftp.php and it will be
used automatically.
Available connection options
• hostname - the FTP hostname. Usually something like: ftp.example.com
• username - the FTP username.
• password - the FTP password.
• port - The port number. Set to 21 by default.
• debug - TRUE/FALSE (boolean). Whether to enable debugging to display error messages.
• passive - TRUE/FALSE (boolean). Whether to use passive mode. Passive is set automatically by default.
$this->ftp->upload()
Uploads a file to your server. You must supply the local path and the remote path, and you can optionally set the mode
and permissions. Example:
120
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->ftp->upload(’/local/path/to/myfile.html’, ’/public_html/myfile.html’, ’ascii’, 0775);
Mode options are: ascii, binary, and auto (the default). If auto is used it will base the mode on the file extension of
the source file.
If set, permissions have to be passed as an octal value.
$this->ftp->download()
Downloads a file from your server. You must supply the remote path and the local path, and you can optionally set the
mode. Example:
$this->ftp->download(’/public_html/myfile.html’, ’/local/path/to/myfile.html’, ’ascii’);
Mode options are: ascii, binary, and auto (the default). If auto is used it will base the mode on the file extension of
the source file.
Returns FALSE if the download does not execute successfully (including if PHP does not have permission to write the
local file)
$this->ftp->rename()
Permits you to rename a file. Supply the source file name/path and the new file name/path.
// Renames green.html to blue.html
$this->ftp->rename(’/public_html/foo/green.html’, ’/public_html/foo/blue.html’);
$this->ftp->move()
Lets you move a file. Supply the source and destination paths:
// Moves blog.html from "joe" to "fred"
$this->ftp->move(’/public_html/joe/blog.html’, ’/public_html/fred/blog.html’);
Note: if the destination file name is different the file will be renamed.
$this->ftp->delete_file()
Lets you delete a file. Supply the source path with the file name.
$this->ftp->delete_file(’/public_html/joe/blog.html’);
$this->ftp->delete_dir()
Lets you delete a directory and everything it contains. Supply the source path to the directory with a trailing slash.
Important Be VERY careful with this function. It will recursively delete everything within the supplied path, including sub-folders and all files. Make absolutely sure your path is correct. Try using the list_files() function first to verify
that your path is correct.
$this->ftp->delete_dir(’/public_html/path/to/folder/’);
7.1. Libraries
121
CodeIgniter Documentation, 3.0-dev
$this->ftp->list_files()
Permits you to retrieve a list of files on your server returned as an array. You must supply the path to the desired
directory.
$list = $this->ftp->list_files(’/public_html/’);
print_r($list);
$this->ftp->mirror()
Recursively reads a local folder and everything it contains (including sub-folders) and creates a mirror via FTP based
on it. Whatever the directory structure of the original file path will be recreated on the server. You must supply a
source path and a destination path:
$this->ftp->mirror(’/path/to/myfolder/’, ’/public_html/myfolder/’);
$this->ftp->mkdir()
Lets you create a directory on your server. Supply the path ending in the folder name you wish to create, with a trailing
slash. Permissions can be set by passed an octal value in the second parameter (if you are running PHP 5).
// Creates a folder named "bar"
$this->ftp->mkdir(’/public_html/foo/bar/’, DIR_WRITE_MODE);
$this->ftp->chmod()
Permits you to set file permissions. Supply the path to the file or folder you wish to alter permissions on:
// Chmod "bar" to 777
$this->ftp->chmod(’/public_html/foo/bar/’, DIR_WRITE_MODE);
$this->ftp->close();
Closes the connection to your server. It’s recommended that you use this when you are finished uploading.
7.1.11 Image Manipulation Class
CodeIgniter’s Image Manipulation class lets you perform the following actions:
• Image Resizing
• Thumbnail Creation
• Image Cropping
• Image Rotating
• Image Watermarking
122
Chapter 7.
CodeIgniter Documentation, 3.0-dev
All three major image libraries are supported: GD/GD2, NetPBM, and ImageMagick
: Watermarking is only available using the GD/GD2 library. In addition, even though other libraries are supported,
GD is required in order for the script to calculate the image properties. The image processing, however, will be
performed with the library you specify.
Initializing the Class
Like most other classes in CodeIgniter, the image class is initialized in your controller using the $this->load->library
function:
$this->load->library(’image_lib’);
Once the library is loaded it will be ready for use. The image library object you will use to call all functions is:
$this->image_lib
Processing an Image
Regardless of the type of processing you would like to perform (resizing, cropping, rotation, or watermarking), the
general process is identical. You will set some preferences corresponding to the action you intend to perform, then
call one of four available processing functions. For example, to create an image thumbnail you’ll do this:
$config[’image_library’] = ’gd2’;
$config[’source_image’] = ’/path/to/image/mypic.jpg’;
$config[’create_thumb’] = TRUE;
$config[’maintain_ratio’] = TRUE;
$config[’width’]
= 75;
$config[’height’]
= 50;
$this->load->library(’image_lib’, $config);
$this->image_lib->resize();
The above code tells the image_resize function to look for an image called mypic.jpg located in the source_image
folder, then create a thumbnail that is 75 X 50 pixels using the GD2 image_library. Since the maintain_ratio option
is enabled, the thumb will be as close to the target width and height as possible while preserving the original aspect
ratio. The thumbnail will be called mypic_thumb.jpg
: In order for the image class to be allowed to do any processing, the folder containing the image files must have write
permissions.
: Image processing can require a considerable amount of server memory for some operations. If you are experiencing
out of memory errors while processing images you may need to limit their maximum size, and/or adjust PHP memory
limits.
Processing Functions
There are four available processing functions:
• $this->image_lib->resize()
• $this->image_lib->crop()
7.1. Libraries
123
CodeIgniter Documentation, 3.0-dev
• $this->image_lib->rotate()
• $this->image_lib->watermark()
• $this->image_lib->clear()
These functions return boolean TRUE upon success and FALSE for failure. If they fail you can retrieve the error
message using this function:
echo $this->image_lib->display_errors();
A good practice is use the processing function conditionally, showing an error upon failure, like this:
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
: You can optionally specify the HTML formatting to be applied to the errors, by submitting the opening/closing tags
in the function, like this:
$this->image_lib->display_errors(’<p>’, ’</p>’);
Preferences
The preferences described below allow you to tailor the image processing to suit your needs.
Note that not all preferences are available for every function. For example, the x/y axis preferences are only available
for image cropping. Likewise, the width and height preferences have no effect on cropping. The “availability” column
indicates which functions support a given preference.
Availability Legend:
• R - Image Resizing
• C - Image Cropping
• X - Image Rotation
• W - Image Watermarking
124
Chapter 7.
CodeIgniter Documentation, 3.0-dev
PrefDeerfault
ence
Value
imGD2
age_library
liNone
brary_path
source_image
None
Options
Description
Availability
GD, GD2,
ImageMagick,
NetPBM
None
Sets the image library to be used.
R, C,
X, W
Sets the server path to your ImageMagick or NetPBM library. If
you use either of those libraries you must supply the path.
R, C, X
R, C,
S, W
None
Sets the source image name/path. The path must be a relative or
absolute server path, not a URL.
dyFALSE TRUE/FALSE Determines whether the new image file should be written to disk or
namic_output
(boolean)
generated dynamically. Note: If you choose the dynamic setting,
only one image can be shown at a time, and it can’t be positioned
on the page. It simply outputs the raw image dynamically to your
browser, along with image headers.
qual90%
1 - 100%
Sets the quality of the image. The higher the quality the larger the
ity
file size.
new_image
None
None
Sets the destination image name/path. You’ll use this preference
when creating an image copy. The path must be a relative or
absolute server path, not a URL.
width
None
None
Sets the width you would like the image set to.
height None
None
Sets the height you would like the image set to.
creFALSE TRUE/FALSE Tells the image processing function to create a thumb.
ate_thumb
(boolean)
thumb_marker
_thumb None
Specifies the thumbnail indicator. It will be inserted just before the
file extension, so mypic.jpg would become mypic_thumb.jpg
mainTRUE TRUE/FALSE Specifies whether to maintain the original aspect ratio when
tain_ratio
(boolean)
resizing or use hard values.
masauto
auto, width,
Specifies what to use as the master axis when resizing or creating
ter_dim
height
thumbs. For example, let’s say you want to resize an image to 100
X 75 pixels. If the source image size does not allow perfect
resizing to those dimensions, this setting determines which axis
should be used as the hard value. “auto” sets the axis automatically
based on whether the image is taller then wider, or vice versa.
rotaNone
90, 180, 270,
Specifies the angle of rotation when rotating images. Note that
tion_angle
vrt, hor
PHP rotates counter-clockwise, so a 90 degree rotation to the right
must be specified as 270.
x_axis None
None
Sets the X coordinate in pixels for image cropping. For example, a
setting of 30 will crop an image 30 pixels from the left.
y_axis None
None
Sets the Y coordinate in pixels for image cropping. For example, a
setting of 30 will crop an image 30 pixels from the top.
R, C,
X, W
R, C,
X, W
R, C,
X, W
R, C
R, C
R
R
R, C
R
X
C
C
Setting preferences in a config file
If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create
a new file called image_lib.php, add the $config array in that file. Then save the file in: config/image_lib.php and
it will be used automatically. You will NOT need to use the $this->image_lib->initialize function if you save your
preferences in a config file.
7.1. Libraries
125
CodeIgniter Documentation, 3.0-dev
$this->image_lib->resize()
The image resizing function lets you resize the original image, create a copy (with or without resizing), or create a
thumbnail image.
For practical purposes there is no difference between creating a copy and creating a thumbnail except a thumb will
have the thumbnail marker as part of the name (ie, mypic_thumb.jpg).
All preferences listed in the table above are available for this function except these three: rotation_angle, x_axis, and
y_axis.
Creating a Thumbnail The resizing function will create a thumbnail file (and preserve the original) if you set this
preference to TRUE:
$config[’create_thumb’] = TRUE;
This single preference determines whether a thumbnail is created or not.
Creating a Copy The resizing function will create a copy of the image file (and preserve the original) if you set a
path and/or a new filename using this preference:
$config[’new_image’] = ’/path/to/new_image.jpg’;
Notes regarding this preference:
• If only the new image name is specified it will be placed in the same folder as the original
• If only the path is specified, the new image will be placed in the destination with the same name as the original.
• If both the path and image name are specified it will placed in its own destination and given the new name.
Resizing the Original Image If neither of the two preferences listed above (create_thumb, and new_image) are
used, the resizing function will instead target the original image for processing.
$this->image_lib->crop()
The cropping function works nearly identically to the resizing function except it requires that you set preferences for
the X and Y axis (in pixels) specifying where to crop, like this:
$config[’x_axis’] = ’100’;
$config[’y_axis’] = ’40’;
All preferences listed in the table above are available for this function except these: rotation_angle, create_thumb,
new_image.
Here’s an example showing how you might crop an image:
$config[’image_library’] = ’imagemagick’;
$config[’library_path’] = ’/usr/X11R6/bin/’;
$config[’source_image’] = ’/path/to/image/mypic.jpg’;
$config[’x_axis’] = ’100’;
$config[’y_axis’] = ’60’;
$this->image_lib->initialize($config);
if ( ! $this->image_lib->crop())
126
Chapter 7.
CodeIgniter Documentation, 3.0-dev
{
echo $this->image_lib->display_errors();
}
: Without a visual interface it is difficult to crop images, so this function is not very useful unless you intend to build
such an interface. That’s exactly what we did using for the photo gallery module in ExpressionEngine, the CMS we
develop. We added a JavaScript UI that lets the cropping area be selected.
$this->image_lib->rotate()
The image rotation function requires that the angle of rotation be set via its preference:
$config[’rotation_angle’] = ’90’;
There are 5 rotation options:
1. 90 - rotates counter-clockwise by 90 degrees.
2. 180 - rotates counter-clockwise by 180 degrees.
3. 270 - rotates counter-clockwise by 270 degrees.
4. hor - flips the image horizontally.
5. vrt - flips the image vertically.
Here’s an example showing how you might rotate an image:
$config[’image_library’] = ’netpbm’;
$config[’library_path’] = ’/usr/bin/’;
$config[’source_image’] = ’/path/to/image/mypic.jpg’;
$config[’rotation_angle’] = ’hor’;
$this->image_lib->initialize($config);
if ( ! $this->image_lib->rotate())
{
echo $this->image_lib->display_errors();
}
$this->image_lib->clear()
The clear function resets all of the values used when processing an image. You will want to call this if you are
processing images in a loop.
$this->image_lib->clear();
Image Watermarking
The Watermarking feature requires the GD/GD2 library.
Two Types of Watermarking
There are two types of watermarking that you can use:
7.1. Libraries
127
CodeIgniter Documentation, 3.0-dev
• Text: The watermark message will be generating using text, either with a True Type font that you specify, or
using the native text output that the GD library supports. If you use the True Type version your GD installation
must be compiled with True Type support (most are, but not all).
• Overlay: The watermark message will be generated by overlaying an image (usually a transparent PNG or GIF)
containing your watermark over the source image.
Watermarking an Image
Just as with the other functions (resizing, cropping, and rotating) the general process for watermarking involves setting
the preferences corresponding to the action you intend to perform, then calling the watermark function. Here is an
example:
$config[’source_image’] = ’/path/to/image/mypic.jpg’;
$config[’wm_text’] = ’Copyright 2006 - John Doe’;
$config[’wm_type’] = ’text’;
$config[’wm_font_path’] = ’./system/fonts/texb.ttf’;
$config[’wm_font_size’] = ’16’;
$config[’wm_font_color’] = ’ffffff’;
$config[’wm_vrt_alignment’] = ’bottom’;
$config[’wm_hor_alignment’] = ’center’;
$config[’wm_padding’] = ’20’;
$this->image_lib->initialize($config);
$this->image_lib->watermark();
The above example will use a 16 pixel True Type font to create the text “Copyright 2006 - John Doe”. The watermark
will be positioned at the bottom/center of the image, 20 pixels from the bottom of the image.
: In order for the image class to be allowed to do any processing, the image file must have “write” file permissions
For example, 777.
Watermarking Preferences
This table shown the preferences that are available for both types of watermarking (text or overlay)
128
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Preference
wm_type
Default
Value
text
source_image
None
Options
Description
text,
overlay
None
Sets the type of watermarking that should be used.
Sets the source image name/path. The path must be a relative or absolute
server path, not a URL.
dyFALSE TRUE/FALSEDetermines whether the new image file should be written to disk or generated
namic_output
(boolean)
dynamically. Note: If you choose the dynamic setting, only one image can
be shown at a time, and it can’t be positioned on the page. It simply outputs
the raw image dynamically to your browser, along with image headers.
quality
90%
1 - 100%
Sets the quality of the image. The higher the quality the larger the file size.
wm_padding
None
A number
The amount of padding, set in pixels, that will be applied to the watermark to
set it away from the edge of your images.
wm_vrt_alignment
bottop,
Sets the vertical alignment for the watermark image.
tom
middle,
bottom
wm_hor_alignment
center
left, center, Sets the horizontal alignment for the watermark image.
right
wm_hor_offset
None
None
You may specify a horizontal offset (in pixels) to apply to the watermark
position. The offset normally moves the watermark to the right, except if you
have your alignment set to “right” then your offset value will move the
watermark toward the left of the image.
wm_vrt_offset
None
None
You may specify a vertical offset (in pixels) to apply to the watermark
position. The offset normally moves the watermark down, except if you have
your alignment set to “bottom” then your offset value will move the
watermark toward the top of the image.
Text Preferences This table shown the preferences that are available for the text type of watermarking.
Preference
wm_text
Default
Value
None
Op- Description
tions
None The text you would like shown as the watermark. Typically this will be a
copyright notice.
wm_font_pathNone
None The server path to the True Type Font you would like to use. If you do not use
this option, the native GD font will be used.
wm_font_size16
None The size of the text. Note: If you are not using the True Type option above, the
number is set using a range of 1 - 5. Otherwise, you can use any valid pixel size
for the font you’re using.
wm_font_color
ffffff
None The font color, specified in hex. Both the full 6-length (ie, 993300) and the short
three character abbreviated version (ie, fff) are supported.
wm_shadow_color
None
None The color of the drop shadow, specified in hex. If you leave this blank a drop
shadow will not be used. Both the full 6-length (ie, 993300) and the short three
character abbreviated version (ie, fff) are supported.
wm_shadow_distance
3
None The distance (in pixels) from the font that the drop shadow should appear.
Overlay Preferences This table shown the preferences that are available for the overlay type of watermarking.
7.1. Libraries
129
CodeIgniter Documentation, 3.0-dev
Preference
Default
Value
wm_overlay_path
None
Options
Description
None
wm_opacity50
1100
wm_x_transp
4
A
number
wm_y_transp
4
A
number
The server path to the image you wish to use as your watermark. Required only if
you are using the overlay method.
Image opacity. You may specify the opacity (i.e. transparency) of your watermark
image. This allows the watermark to be faint and not completely obscure the
details from the original image behind it. A 50% opacity is typical.
If your watermark image is a PNG or GIF image, you may specify a color on the
image to be “transparent”. This setting (along with the next) will allow you to
specify that color. This works by specifying the “X” and “Y” coordinate pixel
(measured from the upper left) within the image that corresponds to a pixel
representative of the color you want to be transparent.
Along with the previous setting, this allows you to specify the coordinate to a pixel
representative of the color you want to be transparent.
7.1.12 Input Class
The Input Class serves two purposes:
1. It pre-processes global input data for security.
2. It provides some helper methods for fetching input data and pre-processing it.
: This class is initialized automatically by the system so there is no need to do it manually.
Security Filtering
The security filtering method is called automatically when a new controller is invoked. It does the following:
• If $config[’allow_get_array’] is FALSE (default is TRUE), destroys the global GET array.
• Destroys all global variables in the event register_globals is turned on.
• Filters the GET/POST/COOKIE array keys, permitting only alpha-numeric (and a few other) characters.
• Provides XSS (Cross-site Scripting Hacks) filtering. This can be enabled globally, or upon request.
• Standardizes newline characters to \n(In Windows \r\n)
XSS Filtering
The Input class has the ability to filter input automatically to prevent cross-site scripting attacks. If you want the
filter to run automatically every time it encounters POST or COOKIE data you can enable it by opening your application/config/config.php file and setting this:
$config[’global_xss_filtering’] = TRUE;
Please refer to the Security class documentation for information on using XSS Filtering in your application.
Using POST, GET, COOKIE, or SERVER Data
CodeIgniter comes with four helper methods that let you fetch POST, GET, COOKIE or SERVER items. The main
advantage of using the provided methods rather than fetching an item directly ($_POST[’something’]) is that
130
Chapter 7.
CodeIgniter Documentation, 3.0-dev
the methods will check to see if the item is set and return NULL if not. This lets you conveniently use data without
having to test whether an item exists first. In other words, normally you might do something like this:
$something = isset($_POST[’something’]) ? $_POST[’something’] : NULL;
With CodeIgniter’s built in methods you can simply do this:
$something = $this->input->post(’something’);
The four methods are:
• $this->input->post()
• $this->input->get()
• $this->input->cookie()
• $this->input->server()
$this->input->post()
The first parameter will contain the name of the POST item you are looking for:
$this->input->post(’some_data’);
The method returns NULL if the item you are attempting to retrieve does not exist.
The second optional parameter lets you run the data through the XSS filter. It’s enabled by setting the second parameter
to boolean TRUE;
$this->input->post(’some_data’, TRUE);
To return an array of all POST items call without any parameters.
To return all POST items and pass them through the XSS filter set the first parameter NULL while setting the second
parameter to boolean;
The method returns NULL if there are no items in the POST.
$this->input->post(NULL, TRUE); // returns all POST items with XSS filter
$this->input->post(); // returns all POST items without XSS filter
$this->input->get()
This method is identical to the POST method, only it fetches GET data
$this->input->get(’some_data’, TRUE);
To return an array of all GET items call without any parameters.
To return all GET items and pass them through the XSS filter set the first parameter NULL while setting the second
parameter to boolean;
The method returns NULL if there are no items in the GET.
$this->input->get(NULL, TRUE); // returns all GET items with XSS filter
$this->input->get(); // returns all GET items without XSS filtering
7.1. Libraries
131
CodeIgniter Documentation, 3.0-dev
$this->input->post_get()
This method will search through both the POST and GET streams for data, looking first in POST, and then in GET:
$this->input->post_get(’some_data’, TRUE);
$this->input->get_post()
This method will search through both the POST and GET streams for data, looking first in GET, and then in POST:
$this->input->get_post(’some_data’, TRUE);
$this->input->cookie()
This method is identical to the POST method, only it fetches cookie data
$this->input->cookie(’some_cookie’);
$this->input->cookie(’some_cookie, TRUE); // with XSS filter
$this->input->server()
This method is identical to the above methods, only it fetches server server data:
$this->input->server(’some_data’);
Using the php://input stream
If you want to utilize the PUT, DELETE, PATCH or other exotic request methods, they can only be accessed via a
special input stream, that can only be read once. This isn’t as easy as just reading from e.g. the $_POST array, because
it will always exist and you can try and access multiple variables without caring that you might only have one shot at
all of the POST data.
CodeIgniter will take care of that for you, and you can access data from the php://input stream at any time, just by
calling the input_stream() method:
$this->input->input_stream(’key’);
Similar to the methods above, if the requested data is not found, it will return NULL and you can also decide whether
to run the data through xss_clean() by passing a boolean value as the second parameter:
$this->input->input_stream(’key’, TRUE); // XSS Clean
$this->input->input_stream(’key’, FALSE); // No XSS filter
: You can utilize method() in order to know if you’re reading PUT, DELETE or PATCH data.
$this->input->set_cookie()
Sets a cookie containing the values you specify. There are two ways to pass information to this method so that a cookie
can be set: Array Method, and Discrete Parameters:
132
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Array Method
Using this method, an associative array is passed to the first parameter:
$cookie = array(
’name’
=> ’The Cookie Name’,
’value’ => ’The Value’,
’expire’ => ’86500’,
’domain’ => ’.some-domain.com’,
’path’
=> ’/’,
’prefix’ => ’myprefix_’,
’secure’ => TRUE
);
$this->input->set_cookie($cookie);
Notes:
Only the name and value are required. To delete a cookie set it with the expiration blank.
The expiration is set in seconds, which will be added to the current time. Do not include the time, but rather only the
number of seconds from now that you wish the cookie to be valid. If the expiration is set to zero the cookie will only
last as long as the browser is open.
For site-wide cookies regardless of how your site is requested, add your URL to the domain starting with a period,
like this: .your-domain.com
The path is usually not needed since the method sets a root path.
The prefix is only needed if you need to avoid name collisions with other identically named cookies for your server.
The secure boolean is only needed if you want to make it a secure cookie by setting it to TRUE.
Discrete Parameters
If you prefer, you can set the cookie by passing data using individual parameters:
$this->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure);
$this->input->ip_address()
Returns the IP address for the current user. If the IP address is not valid, the method will return an IP of: 0.0.0.0
echo $this->input->ip_address();
$this->input->valid_ip($ip)
Takes an IP address as input and returns TRUE or FALSE (boolean) if it is valid or not.
: The $this->input->ip_address() method above automatically validates the IP address.
if ( ! $this->input->valid_ip($ip))
{
echo ’Not Valid’;
}
else
7.1. Libraries
133
CodeIgniter Documentation, 3.0-dev
{
echo ’Valid’;
}
Accepts an optional second string parameter of ‘ipv4’ or ‘ipv6’ to specify an IP format. The default checks for both
formats.
$this->input->user_agent()
Returns the user agent (web browser) being used by the current user. Returns FALSE if it’s not available.
echo $this->input->user_agent();
See the User Agent Class for methods which extract information from the user agent string.
$this->input->request_headers()
Useful if running in a non-Apache environment where apache_request_headers() will not be supported. Returns an
array of headers.
$headers = $this->input->request_headers();
$this->input->get_request_header()
Returns a single member of the request headers array.
$this->input->get_request_header(’some-header’, TRUE);
$this->input->is_ajax_request()
Checks to see if the HTTP_X_REQUESTED_WITH server header has been set, and returns a boolean response.
$this->input->is_cli_request()
Checks to see if the STDIN constant is set, which is a failsafe way to see if PHP is being run on the command line.
$this->input->is_cli_request()
: This method is DEPRECATED and is now just an alias for the is_cli() function.
$this->input->method()
Returns the $_SERVER[’REQUEST_METHOD’], optional set uppercase or lowercase (default lowercase).
echo $this->input->method(TRUE); // Outputs: POST
echo $this->input->method(FALSE); // Outputs: post
echo $this->input->method(); // Outputs: post
: This driver is experimental. Its feature set and implementation may change in future releases.
134
Chapter 7.
CodeIgniter Documentation, 3.0-dev
7.1.13 Javascript Class
CodeIgniter provides a library to help you with certain common functions that you may want to use with Javascript.
Please note that CodeIgniter does not require the jQuery library to run, and that any scripting library will work equally
well. The jQuery library is simply presented as a convenience if you choose to use it.
Initializing the Class
To initialize the Javascript class manually in your controller constructor, use the $this->load->library function. Currently, the only available library is jQuery, which will automatically be loaded like this:
$this->load->library(’javascript’);
The Javascript class also accepts parameters, js_library_driver (string) default ‘jquery’ and autoload (bool) default
TRUE. You may override the defaults if you wish by sending an associative array:
$this->load->library(’javascript’, array(’js_library_driver’ => ’scripto’, ’autoload’ => FALSE));
Again, presently only ‘jquery’ is available. You may wish to set autoload to FALSE, though, if you do not want the
jQuery library to automatically include a script tag for the main jQuery script file. This is useful if you are loading it
from a location outside of CodeIgniter, or already have the script tag in your markup.
Once loaded, the jQuery library object will be available using: $this->javascript
Setup and Configuration
Set these variables in your view
As a Javascript library, your files must be available to your application.
As Javascript is a client side language, the library must be able to write content into your final output. This generally
means a view. You’ll need to include the following variables in the <head> sections of your output.
<?php echo $library_src;?>
<?php echo $script_head;?>
$library_src, is where the actual library file will be loaded, as well as any subsequent plugin script calls; $script_head
is where specific events, functions and other commands will be rendered.
Set the path to the librarys with config items
There are some configuration items in Javascript library. These can either be set in application/config.php, within its
own config/javascript.php file, or within any controller usings the set_item() function.
An image to be used as an “ajax loader”, or progress indicator. Without one, the simple text message of “loading” will
appear when Ajax calls need to be made.
$config[’javascript_location’] = ’http://localhost/codeigniter/themes/js/jquery/’;
$config[’javascript_ajax_img’] = ’images/ajax-loader.gif’;
If you keep your files in the same directories they were downloaded from, then you need not set this configuration
items.
7.1. Libraries
135
CodeIgniter Documentation, 3.0-dev
The jQuery Class
To initialize the jQuery class manually in your controller constructor, use the $this->load->library function:
$this->load->library(’javascript/jquery’);
You may send an optional parameter to determine whether or not a script tag for the main jQuery file will be automatically included when loading the library. It will be created by default. To prevent this, load the library as follows:
$this->load->library(’javascript/jquery’, FALSE);
Once loaded, the jQuery library object will be available using: $this->jquery
jQuery Events
Events are set using the following syntax.
$this->jquery->event(’element_path’, code_to_run());
In the above example:
• “event” is any of blur, change, click, dblclick, error, focus, hover, keydown, keyup, load, mousedown, mouseup,
mouseover, mouseup, resize, scroll, or unload.
• “element_path” is any valid jQuery selector. Due to jQuery’s unique selector syntax, this is usually an element
id, or CSS selector. For example “#notice_area” would effect <div id=”notice_area”>, and “#content a.notice”
would effect all anchors with a class of “notice” in the div with id “content”.
• “code_to_run()” is script your write yourself, or an action such as an effect from the jQuery library below.
Effects
The query library supports a powerful Effects repertoire. Before an effect can be used, it must be loaded:
$this->jquery->effect([optional path] plugin name); // for example $this->jquery->effect(’bounce’);
hide() / show()
Each of this functions will affect the visibility of an item on your page. hide() will set an item invisible, show() will
reveal it.
$this->jquery->hide(target, optional speed, optional extra information);
$this->jquery->show(target, optional speed, optional extra information);
• “target” will be any valid jQuery selector or selectors.
• “speed” is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
• “extra information” is optional, and could include a callback, or other additional information.
toggle()
toggle() will change the visibility of an item to the opposite of its current state, hiding visible elements, and revealing
hidden ones.
136
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->jquery->toggle(target);
• “target” will be any valid jQuery selector or selectors.
animate()
$this->jquery->animate(target, parameters, optional speed, optional extra information);
• “target” will be any valid jQuery selector or selectors.
• “parameters” in jQuery would generally include a series of CSS properties that you wish to change.
• “speed” is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
• “extra information” is optional, and could include a callback, or other additional information.
For a full summary, see http://docs.jquery.com/Effects/animate
Here is an example of an animate() called on a div with an id of “note”, and triggered by a click using the jQuery
library’s click() event.
$params = array(
’height’ => 80,
’width’ => ’50%’,
’marginLeft’ => 125
);
$this->jquery->click(’#trigger’, $this->jquery->animate(’#note’, $params, ’normal’));
fadeIn() / fadeOut()
$this->jquery->fadeIn(target, optional speed, optional extra information);
$this->jquery->fadeOut(target, optional speed, optional extra information);
• “target” will be any valid jQuery selector or selectors.
• “speed” is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
• “extra information” is optional, and could include a callback, or other additional information.
toggleClass()
This function will add or remove a CSS class to its target.
$this->jquery->toggleClass(target, class)
• “target” will be any valid jQuery selector or selectors.
• “class” is any CSS classname. Note that this class must be defined and available in a CSS that is already loaded.
fadeIn() / fadeOut()
These effects cause an element(s) to disappear or reappear over time.
$this->jquery->fadeIn(target, optional speed, optional extra information);
$this->jquery->fadeOut(target, optional speed, optional extra information);
7.1. Libraries
137
CodeIgniter Documentation, 3.0-dev
• “target” will be any valid jQuery selector or selectors.
• “speed” is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
• “extra information” is optional, and could include a callback, or other additional information.
slideUp() / slideDown() / slideToggle()
These effects cause an element(s) to slide.
$this->jquery->slideUp(target, optional speed, optional extra information);
$this->jquery->slideDown(target, optional speed, optional extra information);
$this->jquery->slideToggle(target, optional speed, optional extra information);
• “target” will be any valid jQuery selector or selectors.
• “speed” is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
• “extra information” is optional, and could include a callback, or other additional information.
Plugins
Some select jQuery plugins are made available using this library.
corner()
Used to add distinct corners to page elements. For full details see http://www.malsup.com/jquery/corner/
$this->jquery->corner(target, corner_style);
• “target” will be any valid jQuery selector or selectors.
• “corner_style” is optional, and can be set to any valid style such as round, sharp, bevel, bite, dog, etc. Individual
corners can be set by following the style with a space and using “tl” (top left), “tr” (top right), “bl” (bottom left),
or “br” (bottom right).
$this->jquery->corner("#note", "cool tl br");
tablesorter()
description to come
modal()
description to come
calendar()
description to come
138
Chapter 7.
CodeIgniter Documentation, 3.0-dev
7.1.14 Language Class
The Language Class provides functions to retrieve language files and lines of text for purposes of internationalization.
In your CodeIgniter system folder you’ll find one called language containing sets of language files. You can create
your own language files as needed in order to display error and other messages in other languages.
Language files are typically stored in your system/language/ directory. Alternately you can create a directory called
language inside your application folder and store them there. CodeIgniter will always load the one in system/language/
first and will then look for an override in your application/language/ directory.
:
Each language should be stored in its own folder.
tem/language/english
For example, the English files are located at: sys-
Creating Language Files
Language files must be named with _lang.php as the file extension. For example, let’s say you want to create a file
containing error messages. You might name it: error_lang.php
Within the file you will assign each line of text to an array called $lang with this prototype:
$lang[’language_key’] = ’The actual message to be shown’;
: It’s a good practice to use a common prefix for all messages in a given file to avoid collisions with similarly named
items in other files. For example, if you are creating error messages you might prefix them with error_
$lang[’error_email_missing’] = ’You must submit an email address’;
$lang[’error_url_missing’] = ’You must submit a URL’;
$lang[’error_username_missing’] = ’You must submit a username’;
Loading A Language File
In order to fetch a line from a particular file you must load the file first. Loading a language file is done with the
following code:
$this->lang->load(’filename’, ’language’);
Where filename is the name of the file you wish to load (without the file extension), and language is the language set containing it (ie, english). If the second parameter is missing, the default language set in your application/config/config.php file will be used.
: The language parameter can only consist of letters.
Fetching a Line of Text
Once your desired language file is loaded you can access any line of text using this function:
$this->lang->line(’language_key’);
Where language_key is the array key corresponding to the line you wish to show.
You can optionally pass FALSE as the second argument of that method to disable error logging, in case you’re not
sure if the line exists:
7.1. Libraries
139
CodeIgniter Documentation, 3.0-dev
$this->lang->line(’misc_key’, FALSE);
: This method simply returns the line. It does not echo it.
Using language lines as form labels
This feature has been deprecated from the language library and moved to the lang() function of the Language
Helper.
Auto-loading Languages
If you find that you need a particular language globally throughout your application, you can tell CodeIgniter to autoload it during system initialization. This is done by opening the application/config/autoload.php file and adding the
language(s) to the autoload array.
7.1.15 Loader Class
Loader, as the name suggests, is used to load elements. These elements can be libraries (classes) View files, Drivers,
Helpers, Models, or your own files.
: This class is initialized automatically by the system so there is no need to do it manually.
The following methods are available in this class:
$this->load->library(‘class_name’, $config, ‘object name’)
This method is used to load core classes. Where class_name is the name of the class you want to load.
: We use the terms “class” and “library” interchangeably.
For example, if you would like to send email with CodeIgniter, the first step is to load the email class within your
controller:
$this->load->library(’email’);
Once loaded, the library will be ready for use, using $this->email->*some_method*().
Library files can be stored in subdirectories within the main “libraries” directory, or within your personal application/libraries directory. To load a file located in a subdirectory, simply include the path, relative to the “libraries”
directory. For example, if you have file located at:
libraries/flavors/Chocolate.php
You will load it using:
$this->load->library(’flavors/chocolate’);
You may nest the file in as many subdirectories as you want.
Additionally, multiple libraries can be loaded at the same time by passing an array of libraries to the load method.
140
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->load->library(array(’email’, ’table’));
Setting options
The second (optional) parameter allows you to optionally pass configuration setting. You will typically pass these as
an array:
$config = array (
’mailtype’ => ’html’,
’charset’ => ’utf-8,
’priority’ => ’1’
);
$this->load->library(’email’, $config);
Config options can usually also be set via a config file. Each library is explained in detail in its own page, so please
read the information regarding each one you would like to use.
Please take note, when multiple libraries are supplied in an array for the first parameter, each will receive the same
parameter information.
Assigning a Library to a different object name
If the third (optional) parameter is blank, the library will usually be assigned to an object with the same name as the
library. For example, if the library is named Calendar, it will be assigned to a variable named $this->calendar.
If you prefer to set your own class names you can pass its value to the third parameter:
$this->load->library(’calendar’, ’’, ’my_calendar’);
// Calendar class is now accessed using:
$this->my_calendar
Please take note, when multiple libraries are supplied in an array for the first parameter, this parameter is discarded.
$this->load->driver(‘parent_name’, $config, ‘object name’)
This method is used to load driver libraries. Where parent_name is the name of the parent class you want to load.
As an example, if you would like to use sessions with CodeIgniter, the first step is to load the session driver within
your controller:
$this->load->driver(’session’);
Once loaded, the library will be ready for use, using $this->session->*some_method*().
Driver files must be stored in a subdirectory within the main “libraries” directory, or within your personal application/libraries directory. The subdirectory must match the parent class name. Read the Drivers description for details.
Additionally, multiple driver libraries can be loaded at the same time by passing an array of drivers to the load method.
$this->load->driver(array(’session’, ’cache’));
7.1. Libraries
141
CodeIgniter Documentation, 3.0-dev
Setting options
The second (optional) parameter allows you to optionally pass configuration settings. You will typically pass these as
an array:
$config = array(
’sess_driver’ => ’cookie’,
’sess_encrypt_cookie’ => true,
’encryption_key’ => ’mysecretkey’
);
$this->load->driver(’session’, $config);
Config options can usually also be set via a config file. Each library is explained in detail in its own page, so please
read the information regarding each one you would like to use.
Assigning a Driver to a different object name
If the third (optional) parameter is blank, the library will be assigned to an object with the same name as the parent
class. For example, if the library is named Session, it will be assigned to a variable named $this->session.
If you prefer to set your own class names you can pass its value to the third parameter:
$this->load->library(’session’, ’’, ’my_session’);
// Session class is now accessed using:
$this->my_session
: Driver libraries may also be loaded with the library() method, but it is faster to use driver().
$this->load->view(‘file_name’, $data, TRUE/FALSE)
This method is used to load your View files. If you haven’t read the Views section of the user guide it is recommended
that you do since it shows you how this method is typically used.
The first parameter is required. It is the name of the view file you would like to load.
: The .php file extension does not need to be specified unless you use something other than .php.
The second optional parameter can take an associative array or an object as input, which it runs through the PHP
extract() function to convert to variables that can be used in your view files. Again, read the Views page to learn how
this might be useful.
The third optional parameter lets you change the behavior of the method so that it returns data as a string rather than
sending it to your browser. This can be useful if you want to process the data in some way. If you set the parameter to
true (boolean) it will return data. The default behavior is false, which sends it to your browser. Remember to assign it
to a variable if you want the data returned:
$string = $this->load->view(’myfile’, ’’, true);
142
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->load->model(‘model_name’);
$this->load->model(’model_name’);
If your model is located in a subdirectory, include the relative path from your models directory. For example, if you
have a model located at application/models/blog/Queries.php you’ll load it using:
$this->load->model(’blog/queries’);
If you would like your model assigned to a different object name you can specify it via the second parameter of the
loading method:
$this->load->model(’model_name’, ’fubar’);
$this->fubar->method();
$this->load->database(‘options’, TRUE/FALSE)
This method lets you load the database class. The two parameters are optional. Please see the database section for
more info.
$this->load->vars($array)
This method takes an associative array as input and generates variables using the PHP extract method. This method
produces the same result as using the second parameter of the $this->load->view() method above. The reason
you might want to use this method independently is if you would like to set some global variables in the constructor
of your controller and have them become available in any view file loaded from any method. You can have multiple
calls to this method. The data get cached and merged into one array for conversion to variables.
$this->load->get_var($key)
This method checks the associative array of variables available to your views. This is useful if for any reason a var is
set in a library or another controller method using $this->load->vars().
$this->load->get_vars()
This method retrieves all variables available to your views.
$this->load->clear_vars()
Clears cached view variables.
$this->load->helper(‘file_name’)
This method loads helper files, where file_name is the name of the file, without the _helper.php extension.
$this->load->file(‘filepath/filename’, TRUE/FALSE)
This is a generic file loading method. Supply the filepath and name in the first parameter and it will open and read
the file. By default the data is sent to your browser, just like a View file, but if you set the second parameter to true
(boolean) it will instead return the data as a string.
7.1. Libraries
143
CodeIgniter Documentation, 3.0-dev
$this->load->language(‘file_name’)
This method is an alias of the language loading method: $this->lang->load()
$this->load->config(‘file_name’)
This method is an alias of the config file loading method: $this->config->load()
$this->load->is_loaded(‘library_name’)
The is_loaded() method allows you to check if a class has already been loaded or not.
: The word “class” here refers to libraries and drivers.
If the requested class has been loaded, the method returns its assigned name in the CI Super-object and FALSE if it’s
not:
$this->load->library(’form_validation’);
$this->load->is_loaded(’Form_validation’);
// returns ’form_validation’
$this->load->is_loaded(’Nonexistent_library’);
// returns FALSE
: If you have more than one instance of a class (assigned to different properties), then the first one will be returned.
$this->load->library(’form_validation’, $config, ’fv’);
$this->load->library(’form_validation’);
$this->load->is_loaded(’Form_validation’);
// returns ’fv’
Application “Packages”
An application package allows for the easy distribution of complete sets of resources in a single directory, complete
with its own libraries, models, helpers, config, and language files. It is recommended that these packages be placed in
the application/third_party directory. Below is a sample map of an package directory
Sample Package “Foo Bar” Directory Map
The following is an example of a directory for an application package named “Foo Bar”.
/application/third_party/foo_bar
config/
helpers/
language/
libraries/
models/
Whatever the purpose of the “Foo Bar” application package, it has its own config files, helpers, language files, libraries,
and models. To use these resources in your controllers, you first need to tell the Loader that you are going to be loading
resources from a package, by adding the package path.
144
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->load->add_package_path()
Adding a package path instructs the Loader class to prepend a given path for subsequent requests for resources. As
an example, the “Foo Bar” application package above has a library named Foo_bar.php. In our controller, we’d do the
following:
$this->load->add_package_path(APPPATH.’third_party/foo_bar/’);
$this->load->library(’foo_bar’);
$this->load->remove_package_path()
When your controller is finished using resources from an application package, and particularly if you have other
application packages you want to work with, you may wish to remove the package path so the Loader no longer looks
in that directory for resources. To remove the last path added, simply call the method with no parameters.
$this->load->remove_package_path()
Or to remove a specific package path, specify the same path previously given to add_package_path() for a package.:
$this->load->remove_package_path(APPPATH.’third_party/foo_bar/’);
Package view files
By Default, package view files paths are set when add_package_path() is called. View paths are looped through, and
once a match is encountered that view is loaded.
In this instance, it is possible for view naming collisions within packages to occur, and possibly the incorrect package
being loaded. To ensure against this, set an optional second parameter of FALSE when calling add_package_path().
$this->load->add_package_path(APPPATH.’my_app’, FALSE);
$this->load->view(’my_app_index’); // Loads
$this->load->view(’welcome_message’); // Will not load the default welcome_message b/c the second par
// Reset things
$this->load->remove_package_path(APPPATH.’my_app’);
// Again without the second parameter:
$this->load->add_package_path(APPPATH.’my_app’);
$this->load->view(’my_app_index’); // Loads
$this->load->view(’welcome_message’); // Loads
7.1.16 Migrations Class
Migrations are a convenient way for you to alter your database in a structured and organized manner. You could edit
fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run
them. You would also have to keep track of which changes need to be run against the production machines next time
you deploy.
The database table migration tracks which migrations have already been run so all you have to do is update your
application files and call $this->migration->current() to work out which migrations should be run. The current
version is found in config/migration.php.
7.1. Libraries
145
CodeIgniter Documentation, 3.0-dev
Migration file names
Each Migration is run in numeric order forward or backwards depending on the method taken. Two numbering styles
are available:
• Sequential: each migration is numbered in sequence, starting with 001. Each number must be three digits, and
there must not be any gaps in the sequence. (This was the numbering scheme prior to CodeIgniter 3.0.)
• Timestamp: each migration is numbered using the timestamp when the migration was created, in YYYYMMDDHHIISS format (e.g. 20121031100537). This helps prevent numbering conflicts when working in a team
environment, and is the preferred scheme in CodeIgniter 3.0 and later.
The desired style may be selected using the $config[’migration_type’] setting in your migration.php config file.
Regardless of which numbering style you choose to use, prefix your migration files with the migration number followed
by an underscore and a descriptive name for the migration. For example:
• 001_add_blog.php (sequential numbering)
• 20121031100537_add_blog.php (timestamp numbering)
Create a Migration
This will be the first migration for a new site which has a blog. All migrations go in the folder application/migrations/
and have names such as 20121031100537_add_blog.php.:
<?php
defined(’BASEPATH’) OR exit(’No direct script access allowed’);
class Migration_Add_blog extends CI_Migration {
public function up()
{
$this->dbforge->add_field(array(
’blog_id’ => array(
’type’ => ’INT’,
’constraint’ => 5,
’unsigned’ => TRUE,
’auto_increment’ => TRUE
),
’blog_title’ => array(
’type’ => ’VARCHAR’,
’constraint’ => ’100’,
),
’blog_description’ => array(
’type’ => ’TEXT’,
’null’ => TRUE,
),
));
$this->dbforge->add_key(’blog_id’, TRUE);
$this->dbforge->create_table(’blog’);
}
public function down()
{
$this->dbforge->drop_table(’blog’);
}
}
146
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Then in application/config/migration.php set $config[’migration_version’] = 1;.
Usage Example
In this example some simple code is placed in application/controllers/Migrate.php to update the schema.:
<?php
class Migrate extends CI_Controller
{
public function index()
{
$this->load->library(’migration’);
if ($this->migration->current() === FALSE)
{
show_error($this->migration->error_string());
}
}
}
Function Reference
$this->migration->current()
The current migration is whatever is set for $config[’migration_version’] in application/config/migration.php.
$this->migration->error_string()
This returns a string of errors while performing a migration.
$this->migration->find_migrations()
An array of migration filenames are returned that are found in the migration_path property.
$this->migration->latest()
This works much the same way as current() but instead of looking for the $config[’migration_version’] the Migration
class will use the very newest migration found in the filesystem.
$this->migration->version()
Version can be used to roll back changes or step forwards programmatically to specific versions. It works just like
current but ignores $config[’migration_version’].:
$this->load->library(’migration’);
$this->migration->version(5);
7.1. Libraries
147
CodeIgniter Documentation, 3.0-dev
Migration Preferences
The following is a table of all the config options for migrations.
Preference
migration_enabled
migration_path
migration_version
migration_table
migration_auto_latest
migration_type
Default
FALSE
Options
TRUE / FALSE
Description
Enable or disable migrations.
APPPATH.’migrations/’
0
None
The path to your migrations folder.
None
The current version your database should use.
migrations
None
FALSE
TRUE / FALSE
‘timestamp’
‘timestamp’ /
‘sequential’
The table name for storing the schema version
number.
Enable or disable automatically running
migrations.
The type of numeric identifier used to name
migration files.
7.1.17 Output Class
The Output class is a small class with one main function: To send the finalized web page to the requesting browser. It
is also responsible for caching your web pages, if you use that feature.
: This class is initialized automatically by the system so there is no need to do it manually.
Under normal circumstances you won’t even notice the Output class since it works transparently without your intervention. For example, when you use the Loader class to load a view file, it’s automatically passed to the Output class,
which will be called automatically by CodeIgniter at the end of system execution. It is possible, however, for you to
manually intervene with the output if you need to, using either of the two following functions:
$this->output->set_output();
Permits you to manually set the final output string. Usage example:
$this->output->set_output($data);
: If you do set your output manually, it must be the last thing done in the function you call it from. For example, if
you build a page in one of your controller functions, don’t set the output until the end.
$this->output->set_content_type();
Permits you to set the mime-type of your page so you can serve JSON data, JPEG’s, XML, etc easily.
$this->output
->set_content_type(’application/json’)
->set_output(json_encode(array(’foo’ => ’bar’)));
$this->output
->set_content_type(’jpeg’) // You could also use ".jpeg" which will have the full stop removed be
->set_output(file_get_contents(’files/something.jpg’));
148
Chapter 7.
CodeIgniter Documentation, 3.0-dev
: Make sure any non-mime string you pass to this method exists in config/mimes.php or it will have no effect.
You can also set the character set of the document, by passing a second argument:
$this->output->set_content_type(’css’, ’utf-8’);
$this->output->get_content_type()
Returns the Content-Type HTTP header that’s currently in use, excluding the character set value.
$mime = $this->output->get_content_type();
: If not set, the default return value is ‘text/html’.
$this->output->get_header()
Gets the requested HTTP header value, if set.
If the header is not set, NULL will be returned. If an empty value is passed to the method, it will return FALSE.
Example:
$this->output->set_content_type(’text/plain’, ’UTF-8’);
echo $this->output->get_header(’content-type’);
// Outputs: text/plain; charset=utf-8
: The header name is compared in a case-insensitive manner.
: Raw headers sent via PHP’s native header() function are also detected.
$this->output->get_output()
Permits you to manually retrieve any output that has been sent for storage in the output class. Usage example:
$string = $this->output->get_output();
Note that data will only be retrievable from this function if it has been previously sent to the output class by one of the
CodeIgniter functions like $this->load->view().
$this->output->append_output();
Appends data onto the output string. Usage example:
$this->output->append_output($data);
$this->output->set_header();
Permits you to manually set server headers, which the output class will send for you when outputting the final rendered
display. Example:
7.1. Libraries
149
CodeIgniter Documentation, 3.0-dev
$this->output->set_header("HTTP/1.0 200 OK");
$this->output->set_header("HTTP/1.1 200 OK");
$this->output->set_header(’Last-Modified: ’.gmdate(’D, d M Y H:i:s’, $last_update).’ GMT’);
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
$this->output->set_header("Cache-Control: post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
$this->output->set_status_header(code, ‘text’);
Permits you to manually set a server status header. Example:
$this->output->set_status_header(’401’);
// Sets the header as: Unauthorized
See here for a full list of headers.
: This method is an alias for Common function set_status_header().
$this->output->enable_profiler();
Permits you to enable/disable the Profiler, which will display benchmark and other data at the bottom of your pages
for debugging and optimization purposes.
To enable the profiler place the following function anywhere within your Controller functions:
$this->output->enable_profiler(TRUE);
When enabled a report will be generated and inserted at the bottom of your pages.
To disable the profiler you will use:
$this->output->enable_profiler(FALSE);
$this->output->set_profiler_sections();
Permits you to enable/disable specific sections of the Profiler when enabled. Please refer to the Profiler documentation
for further information.
$this->output->cache();
The CodeIgniter output library also controls caching. For more information, please see the caching documentation.
Parsing Execution Variables
CodeIgniter will parse the pseudo-variables {elapsed_time} and {memory_usage} in your output by default. To disable
this, set the $parse_exec_vars class property to FALSE in your controller.
$this->output->parse_exec_vars = FALSE;
150
Chapter 7.
CodeIgniter Documentation, 3.0-dev
7.1.18 Pagination Class
CodeIgniter’s Pagination class is very easy to use, and it is 100% customizable, either dynamically or via stored
preferences.
If you are not familiar with the term “pagination”, it refers to links that allows you to navigate from page to page, like
this:
« First
< 1 2 3 4 5 >
Last »
Example
Here is a simple example showing how to create pagination in one of your controller functions:
$this->load->library(’pagination’);
$config[’base_url’] = ’http://example.com/index.php/test/page/’;
$config[’total_rows’] = 200;
$config[’per_page’] = 20;
$this->pagination->initialize($config);
echo $this->pagination->create_links();
Notes
The $config array contains your configuration variables. It is passed to the $this->pagination->initialize function as
shown above. Although there are some twenty items you can configure, at minimum you need the three shown. Here
is a description of what those items represent:
• base_url This is the full URL to the controller class/function containing your pagination. In the example above,
it is pointing to a controller called “Test” and a function called “page”. Keep in mind that you can re-route your
URI if you need a different structure.
• total_rows This number represents the total rows in the result set you are creating pagination for. Typically this
number will be the total rows that your database query returned.
• per_page The number of items you intend to show per page. In the above example, you would be showing 20
items per page.
The create_links() function returns an empty string when there is no pagination to show.
Setting preferences in a config file
If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create
a new file called pagination.php, add the $config array in that file. Then save the file in: config/pagination.php and
it will be used automatically. You will NOT need to use the $this->pagination->initialize function if you save your
preferences in a config file.
Customizing the Pagination
The following is a list of all the preferences you can pass to the initialization function to tailor the display.
7.1. Libraries
151
CodeIgniter Documentation, 3.0-dev
$config[’uri_segment’] = 3;
The pagination function automatically determines which segment of your URI contains the page number. If you need
something different you can specify it.
$config[’num_links’] = 2;
The number of “digit” links you would like before and after the selected page number. For example, the number 2 will
place two digits on either side, as in the example links at the very top of this page.
$config[’use_page_numbers’] = TRUE;
By default, the URI segment will use the starting index for the items you are paginating. If you prefer to show the the
actual page number, set this to TRUE.
$config[’page_query_string’] = TRUE;
By default, the pagination library assume you are using URI Segments, and constructs your links something like
http://example.com/index.php/test/page/20
If you have $config[’enable_query_strings’] set to TRUE your links will automatically be re-written using Query
Strings. This option can also be explictly set. Using $config[’page_query_string’] set to TRUE, the pagination link
will become.
http://example.com/index.php?c=test&m=page&per_page=20
Note that “per_page” is the default query string passed,
fig[’query_string_segment’] = ‘your_string’
however can be configured using $con-
$config[’reuse_query_string’] = FALSE;
By default your Query String arguments (nothing to do with other query string options) will be ignored. Setting this
config to TRUE will add existing query string arguments back into the URL after the URI segment and before the
suffix
http://example.com/index.php/test/page/20?query=search%term
This helps you mix together normal URI Segments as well as query string arguments, which until 3.0 was not possible.
$config[’prefix’] = ‘’;
A custom prefix added to the path. The prefix value will be right before the offset segment.
$config[’suffix’] = ‘’;
A custom suffix added to the path. The sufix value will be right after the offset segment.
152
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Adding Enclosing Markup
If you would like to surround the entire pagination with some markup you can do it with these two prefs:
$config[’full_tag_open’] = ‘<p>’;
The opening tag placed on the left side of the entire result.
$config[’full_tag_close’] = ‘</p>’;
The closing tag placed on the right side of the entire result.
Customizing the First Link
$config[’first_link’] = ‘First’;
The text you would like shown in the “first” link on the left. If you do not want this link rendered, you can set its value
to FALSE.
$config[’first_tag_open’] = ‘<div>’;
The opening tag for the “first” link.
$config[’first_tag_close’] = ‘</div>’;
The closing tag for the “first” link.
Customizing the Last Link
$config[’last_link’] = ‘Last’;
The text you would like shown in the “last” link on the right. If you do not want this link rendered, you can set its
value to FALSE.
$config[’last_tag_open’] = ‘<div>’;
The opening tag for the “last” link.
$config[’last_tag_close’] = ‘</div>’;
The closing tag for the “last” link.
7.1. Libraries
153
CodeIgniter Documentation, 3.0-dev
Customizing the “Next” Link
$config[’next_link’] = ‘&gt;’;
The text you would like shown in the “next” page link. If you do not want this link rendered, you can set its value to
FALSE.
$config[’next_tag_open’] = ‘<div>’;
The opening tag for the “next” link.
$config[’next_tag_close’] = ‘</div>’;
The closing tag for the “next” link.
Customizing the “Previous” Link
$config[’prev_link’] = ‘&lt;’;
The text you would like shown in the “previous” page link. If you do not want this link rendered, you can set its value
to FALSE.
$config[’prev_tag_open’] = ‘<div>’;
The opening tag for the “previous” link.
$config[’prev_tag_close’] = ‘</div>’;
The closing tag for the “previous” link.
Customizing the “Current Page” Link
$config[’cur_tag_open’] = ‘<b>’;
The opening tag for the “current” link.
$config[’cur_tag_close’] = ‘</b>’;
The closing tag for the “current” link.
Customizing the “Digit” Link
$config[’num_tag_open’] = ‘<div>’;
The opening tag for the “digit” link.
154
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$config[’num_tag_close’] = ‘</div>’;
The closing tag for the “digit” link.
Hiding the Pages
If you wanted to not list the specific pages (for example, you only want “next” and “previous” links), you can suppress
their rendering by adding:
$config[’display_pages’] = FALSE;
Adding attributes to anchors
If you want to add an extra attribute to be added to every link rendered by the pagination class, you can set them as
key/value pairs in the “attributes” config
// Produces: class="myclass"
$config[’attributes’] = array(’class’ => ’myclass’);
: Usage of the old method of setting classes via “anchor_class” is deprecated.
Disabling the “rel” attribute
By default the rel attribute is dynamically generated and appended to the appropriate anchors. If for some reason you
want to turn it off, you can pass boolean FALSE as a regular attribute
$config[’attributes’][’rel’] = FALSE;
7.1.19 Template Parser Class
The Template Parser Class enables you to parse pseudo-variables contained within your view files. It can parse simple
variables or variable tag pairs. If you’ve never used a template engine, pseudo-variables look like this:
<html>
<head>
<title>{blog_title}</title>
</head>
<body>
<h3>{blog_heading}</h3>
{blog_entries}
<h5>{title}</h5>
<p>{body}</p>
{/blog_entries}
</body>
</html>
These variables are not actual PHP variables, but rather plain text representations that allow you to eliminate PHP
from your templates (view files).
: CodeIgniter does not require you to use this class since using pure PHP in your view pages lets them run a little
7.1. Libraries
155
CodeIgniter Documentation, 3.0-dev
faster. However, some developers prefer to use a template engine if they work with designers who they feel would find
some confusion working with PHP.
: The Template Parser Class is not a full-blown template parsing solution. We’ve kept it very lean on purpose in order
to maintain maximum performance.
Initializing the Class
Like most other classes in CodeIgniter, the Parser class is initialized in your controller using the $this->load->library
function:
$this->load->library(’parser’);
Once loaded, the Parser library object will be available using: $this->parser
The following functions are available in this library:
$this->parser->parse()
This method accepts a template name and data array as input, and it generates a parsed version. Example:
$this->load->library(’parser’);
$data = array(
’blog_title’ => ’My Blog Title’,
’blog_heading’ => ’My Blog Heading’
);
$this->parser->parse(’blog_template’, $data);
The first parameter contains the name of the view file (in this example the file would be called blog_template.php), and
the second parameter contains an associative array of data to be replaced in the template. In the above example, the
template would contain two variables: {blog_title} and {blog_heading}
There is no need to “echo” or do something with the data returned by $this->parser->parse(). It is automatically passed
to the output class to be sent to the browser. However, if you do want the data returned instead of sent to the output
class you can pass TRUE (boolean) to the third parameter:
$string = $this->parser->parse(’blog_template’, $data, TRUE);
$this->parser->parse_string()
This method works exactly like parse(), only accepts a string as the first parameter in place of a view file.
Variable Pairs
The above example code allows simple variables to be replaced. What if you would like an entire block of variables
to be repeated, with each iteration containing new values? Consider the template example we showed at the top of the
page:
156
Chapter 7.
CodeIgniter Documentation, 3.0-dev
<html>
<head>
<title>{blog_title}</title>
</head>
<body>
<h3>{blog_heading}</h3>
{blog_entries}
<h5>{title}</h5>
<p>{body}</p>
{/blog_entries}
</body>
</html>
In the above code you’ll notice a pair of variables: {blog_entries} data... {/blog_entries}. In a case like this, the entire
chunk of data between these pairs would be repeated multiple times, corresponding to the number of rows in a result.
Parsing variable pairs is done using the identical code shown above to parse single variables, except, you will add a
multi-dimensional array corresponding to your variable pair data. Consider this example:
$this->load->library(’parser’);
$data = array(
’blog_title’
=> ’My Blog Title’,
’blog_heading’ => ’My Blog Heading’,
’blog_entries’ => array(
array(’title’
array(’title’
array(’title’
array(’title’
array(’title’
)
);
=>
=>
=>
=>
=>
’Title
’Title
’Title
’Title
’Title
1’,
2’,
3’,
4’,
5’,
’body’
’body’
’body’
’body’
’body’
=>
=>
=>
=>
=>
’Body
’Body
’Body
’Body
’Body
1’),
2’),
3’),
4’),
5’)
$this->parser->parse(’blog_template’, $data);
If your “pair” data is coming from a database result, which is already a multi-dimensional array, you can simply use
the database result_array() function:
$query = $this->db->query("SELECT * FROM blog");
$this->load->library(’parser’);
$data = array(
’blog_title’
=> ’My Blog Title’,
’blog_heading’ => ’My Blog Heading’,
’blog_entries’ => $query->result_array()
);
$this->parser->parse(’blog_template’, $data);
7.1.20 Security Class
The Security Class contains methods that help you create a secure application, processing input data for security.
7.1. Libraries
157
CodeIgniter Documentation, 3.0-dev
XSS Filtering
CodeIgniter comes with a Cross Site Scripting Hack prevention filter which can either run automatically to filter all
POST and COOKIE data that is encountered, or you can run it on a per item basis. By default it does not run globally
since it requires a bit of processing overhead, and since you may not need it in all cases.
The XSS filter looks for commonly used techniques to trigger Javascript or other types of code that attempt to hijack
cookies or do other malicious things. If anything disallowed is encountered it is rendered safe by converting the data
to character entities.
Note: This function should only be used to deal with data upon submission. It’s not something that should be used for
general runtime processing since it requires a fair amount of processing overhead.
To filter data through the XSS filter use this function:
$this->security->xss_clean()
Here is an usage example:
$data = $this->security->xss_clean($data);
If you want the filter to run automatically every time it encounters POST or COOKIE data you can enable it by opening
your application/config/config.php file and setting this:
$config[’global_xss_filtering’] = TRUE;
Note: If you use the form validation class, it gives you the option of XSS filtering as well.
An optional second parameter, is_image, allows this function to be used to test images for potential XSS attacks, useful
for file upload security. When this second parameter is set to TRUE, instead of returning an altered string, the function
returns TRUE if the image is safe, and FALSE if it contained potentially malicious information that a browser may
attempt to execute.
if ($this->security->xss_clean($file, TRUE) === FALSE)
{
// file failed the XSS test
}
$this->security->sanitize_filename()
When accepting filenames from user input, it is best to sanitize them to prevent directory traversal and other security
related issues. To do so, use the sanitize_filename() method of the Security class. Here is an example:
$filename = $this->security->sanitize_filename($this->input->post(’filename’));
If it is acceptable for the user input to include relative paths, e.g. file/in/some/approved/folder.txt, you can set the
second optional parameter, $relative_path to TRUE.
$filename = $this->security->sanitize_filename($this->input->post(’filename’), TRUE);
Cross-site request forgery (CSRF)
You can enable CSRF protection by opening your application/config/config.php file and setting this:
$config[’csrf_protection’] = TRUE;
158
Chapter 7.
CodeIgniter Documentation, 3.0-dev
If you use the form helper, then form_open() will automatically insert a hidden csrf field in your forms. If not,
then you can use csrf_get_token_name() and csrf_get_hash()
$csrf = array(
’name’ => $this->security->csrf_get_token_name(),
’hash’ => $this->security->csrf_get_hash()
);
...
<input type="hidden" name="<?=$csrf[’name’];?>" value="<?=$csrf[’hash’];?>" />
Tokens may be either regenerated on every submission (default) or kept the same throughout the life of the CSRF
cookie. The default regeneration of tokens provides stricter security, but may result in usability concerns as other
tokens become invalid (back/forward navigation, multiple tabs/windows, asynchronous actions, etc). You may alter
this behavior by editing the following config parameter
$config[’csrf_regeneration’] = TRUE;
Select URIs can be whitelisted from csrf protection (for example API endpoints expecting externally POSTed content).
You can add these URIs by editing the ‘csrf_exclude_uris’ config parameter:
$config[’csrf_exclude_uris’] = array(’api/person/add’);
$this->security->get_csrf_token_name()
Returns the CSRF token name, which is set by $config[’csrf_token_name’].
$this->security->get_csrf_hash()
Returns the CSRF hash value. Useful in combination with get_csrf_token_name() for manually building
forms or sending valid AJAX POST requests.
7.1.21 Session Driver
The Session class permits you maintain a user’s “state” and track their activity while they browse your site. CodeIgniter
offers two default session drivers: the classic Cookie Driver, and the Native Driver, which supports usage of the native
PHP Session mechanism. In addition, you may create your own Custom Drivers to store session data however you
wish, while still taking advantage of the features of the Session class.
Initializing a Session
Sessions will typically run globally with each page load, so the session class must either be initialized in your controller
constructors, or it can be auto-loaded by the system. For the most part the session class will run unattended in the
background, so simply initializing the class will cause it to read, create, and update sessions.
To initialize the Session class manually in your controller constructor, use the $this->load->driver function:
$this->load->driver(’session’);
Once loaded, the Sessions library object will be available using: $this->session
7.1. Libraries
159
CodeIgniter Documentation, 3.0-dev
How do Sessions work?
When a page is loaded, the session class will check to see if valid session data exists in the user’s session. If sessions
data does not exist (or if it has expired) a new session will be created and saved. If a session does exist, its information
will be updated. With each update, the session_id will be regenerated.
It’s important for you to understand that once initialized, the Session class runs automatically. There is nothing you
need to do to cause the above behavior to happen. You can, as you’ll see below, work with session data or even add
your own data to a user’s session, but the process of reading, writing, and updating a session is automatic.
What is Session Data?
A session, as far as CodeIgniter is concerned, is simply an array containing the following information:
• The user’s unique Session ID (this is a statistically random string with very strong entropy, hashed with MD5
for portability, and regenerated (by default) every five minutes)
• The user’s IP Address
• The user’s User Agent data (the first 120 characters of the browser data string)
• The “last activity” time stamp.
The above data is stored in a cookie as a serialized array with this prototype:
[array]
(
’session_id’
’ip_address’
’user_agent’
’last_activity’
)
=>
=>
=>
=>
random hash,
’string - user IP address’,
’string - user agent data’,
timestamp
: Sessions are only updated every five minutes by default to reduce processor load. If you repeatedly reload a
page you’ll notice that the “last activity” time only updates if five minutes or more has passed since the last time
the cookie was written. This time is configurable by changing the $config[’sess_time_to_update’] line in your system/config/config.php file.
Retrieving Session Data
Any piece of information from the session array is available using the following function:
$this->session->userdata(’item’);
Where item is the array index corresponding to the item you wish to fetch. For example, to fetch the session ID you
will do this:
$session_id = $this->session->userdata(’session_id’);
: The function returns NULL if the item you are trying to access does not exist.
Adding Custom Session Data
A useful aspect of the session array is that you can add your own data to it and it will be stored in the user’s cookie.
Why would you want to do this? Here’s one example:
160
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Let’s say a particular user logs into your site. Once authenticated, you could add their username and email address to
the session, making that data globally available to you without having to run a database query when you need it.
To add your data to the session array involves passing an array containing your new data to this function:
$this->session->set_userdata($array);
Where $array is an associative array containing your new data. Here’s an example:
$newdata = array(
’username’ => ’johndoe’,
’email’
=> ’johndoe@some-site.com’,
’logged_in’ => TRUE
);
$this->session->set_userdata($newdata);
If you want to add userdata one value at a time, set_userdata() also supports this syntax.
$this->session->set_userdata(’some_name’, ’some_value’);
If you want to verify that a userdata value exists, call has_userdata().
$this->session->has_userdata(’some_name’);
Retrieving All Session Data
An array of all userdata can be retrieved as follows:
$this->session->all_userdata()
And returns an associative array like the following:
Array
(
[session_id] =>
[ip_address] =>
[user_agent] =>
[last_activity]
)
4a5a5dca22728fb0a84364eeb405b601
127.0.0.1
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7;
=> 1303142623
Removing Session Data
Just as set_userdata() can be used to add information into a session, unset_userdata() can be used to remove it, by
passing the session key. For example, if you wanted to remove ‘some_name’ from your session information:
$this->session->unset_userdata(’some_name’);
This function can also be passed an associative array of items to unset.
$array_items = array(’username’ => ’’, ’email’ => ’’);
$this->session->unset_userdata($array_items);
7.1. Libraries
161
CodeIgniter Documentation, 3.0-dev
Flashdata
CodeIgniter supports “flashdata”, or session data that will only be available for the next server request, and are then
automatically cleared. These can be very useful, and are typically used for informational or status messages (for
example: “record 2 deleted”).
: Flash variables are prefaced with “flash_” so avoid this prefix in your own session names.
To add flashdata:
$this->session->set_flashdata(’item’, ’value’);
You can also pass an array to set_flashdata(), in the same manner as set_userdata().
To read a flashdata variable:
$this->session->flashdata(’item’);
An array of all flashdata can be retrieved as follows:
$this->session->all_flashdata();
If you find that you need to preserve a flashdata variable through an additional request, you can do so using the
keep_flashdata() function. You can either pass a single item or an array of flashdata items to keep.
$this->session->keep_flashdata(’item’);
$this->session->keep_flashdata(array(’item1’, ’item2’, ’item3’));
Tempdata
CodeIgniter also supports “tempdata”, or session data with a specific expiration time. After the value expires, or the
session expires or is deleted, the value is automatically removed.
To add tempdata:
$expire = 300;
// Expire in 5 minutes
$this->session->set_tempdata(’item’, ’value’, $expire);
You can also pass an array to set_tempdata():
$tempdata = array(’newuser’ => TRUE, ’message’ => ’Thanks for joining!’);
$this->session->set_tempdata($tempdata, ’’, $expire);
: If the expiration is omitted or set to 0, the default expiration of 5 minutes will be used.
To read a tempdata variable:
$this->session->tempdata(’item’);
If you need to remove a tempdata value before it expires, use unset_tempdata():
$this->session->unset_tempdata(’item’);
162
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Destroying a Session
To clear the current session:
$this->session->sess_destroy();
: This function should be the last one called, and even flash variables will no longer be available. If you only want
some items destroyed and not all, use unset_userdata().
Session Preferences
You’ll find the following Session related preferences in your application/config/config.php file:
PreferDeOptions
Description
ence
fault
sess_driver cookie cookie/native/custom
The initial session driver to load.
sess_valid_drivers
cookie, None
Additional valid drivers which may be loaded.
native
sess_cookie_name
ci_sessionNone
The name you want the session cookie saved as (data for Cookie driver or
session ID for Native driver).
sess_expiration
7200
None
The number of seconds you would like the session to last. The default value
is 2 hours (7200 seconds). If you would like a non-expiring session set the
value to zero: 0
sess_expire_on_close
FALSE TRUE/FALSE Whether to cause the session to expire automatically when the browser
(boolean)
window is closed.
sess_encrypt_cookie
FALSE TRUE/FALSE Whether to encrypt the session data (Cookie driver only).
(boolean)
sess_use_database
FALSE TRUE/FALSE Whether to save the session data to a database. You must create the table
(boolean)
before enabling this option (Cookie driver only).
sess_table_name
ci_sessions
Any valid
The name of the session database table (Cookie driver only).
SQL table
name
sess_time_to_update
300
Time in
This options controls how often the session class will regenerate itself and
seconds
create a new session ID. Setting it to 0 will disable session ID regeneartion.
sess_match_ip
FALSE TRUE/FALSE Whether to match the user’s IP address when reading the session data. Note
(boolean)
that some ISPs dynamically changes the IP, so if you want a non-expiring
session you will likely set this to FALSE.
sess_match_useragent
TRUE TRUE/FALSE Whether to match the User Agent when reading the session data.
(boolean)
In addition to the values above, the cookie and native drivers apply the following configuration values shared by the
Input and Security classes:
Preference
cookie_prefix
cookie_domain
cookie_path
Default
‘’
‘’
/
Description
Set a cookie name prefix in order to avoid name collisions
The domain for which the session is applicable
The path to which the session is applicable
Session Drivers
By default, the Cookie Driver is loaded when a session is initialized. However, any valid driver may be selected with
the $config[’sess_driver’] line in your config.php file.
7.1. Libraries
163
CodeIgniter Documentation, 3.0-dev
The session driver library comes with the cookie and native drivers installed, and Custom Drivers may also be installed
by the user.
Typically, only one driver will be used at a time, but CodeIgniter does support loading multiple drivers. If a specific
valid driver is called, it will be automatically loaded. Or, an additional driver may be explicitly loaded by calling
load_driver():
$this->session->load_driver(’native’);
The Session library keeps track of the most recently selected driver to call for driver methods. Normally, session class
methods are called directly on the parent class, as illustrated above. However, any methods called through a specific
driver will select that driver before invoking the parent method.
So, alternation between multiple drivers can be achieved by specifying which driver to use for each call:
$this->session->native->set_userdata(’foo’, ’bar’);
$this->session->cookie->userdata(’foo’);
$this->session->native->unset_userdata(’foo’);
Notice in the previous example that the native userdata value ‘foo’ would be set to ‘bar’, which would NOT be returned
by the call for the cookie userdata ‘foo’, nor would the cookie value be unset by the call to unset the native ‘foo’ value.
The drivers maintain independent sets of values, regardless of key names.
A specific driver may also be explicitly selected for use by pursuant methods with the select_driver() call:
$this->session->select_driver(’native’);
$this->session->userdata(’item’);
// Uses the native driver
Cookie Driver
The Cookie driver stores session information for each user as serialized (and optionally encrypted) data in a cookie. It
can also store the session data in a database table for added security, as this permits the session ID in the user’s cookie
to be matched against the stored session ID. By default only the cookie is saved. If you choose to use the database
option you’ll need to create the session table as indicated below.
If you have the encryption option enabled, the serialized array will be encrypted before being stored in the cookie,
making the data highly secure and impervious to being read or altered by someone. More info regarding encryption
can be found here, although the Session class will take care of initializing and encrypting the data automatically.
: Even if you are not using encrypted sessions, you must set an encryption key in your config file which is used to aid
in preventing session data manipulation.
: Cookies can only hold 4KB of data, so be careful not to exceed the capacity. The encryption process in particular
produces a longer data string than the original so keep careful track of how much data you are storing.
Saving Session Data to a Database While the session data array stored in the user’s cookie contains a Session ID,
unless you store session data in a database there is no way to validate it. For some applications that require little or no
security, session ID validation may not be needed, but if your application requires security, validation is mandatory.
Otherwise, an old session could be restored by a user modifying their cookies.
When session data is available in a database, every time a valid session is found in the user’s cookie, a database query
is performed to match it. If the session ID does not match, the session is destroyed. Session IDs can never be updated,
they can only be generated when a new session is created.
164
Chapter 7.
CodeIgniter Documentation, 3.0-dev
In order to store sessions, you must first create a database table for this purpose. Here is the basic prototype (for
MySQL) required by the session class:
CREATE TABLE IF NOT EXISTS ‘ci_sessions‘ (
session_id varchar(40) DEFAULT ’0’ NOT NULL,
ip_address varchar(45) DEFAULT ’0’ NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id, ip_address, user_agent),
KEY ‘last_activity_idx‘ (‘last_activity‘)
);
: By default the table is called ci_sessions, but you can name it anything you want as long as you update the
application/config/config.php file so that it contains the name you have chosen. Once you have created your database
table you can enable the database option in your config.php file as follows:
$config[’sess_use_database’] = TRUE;
Once enabled, the Session class will store session data in the DB.
Make sure you’ve specified the table name in your config file as well:
$config[’sess_table_name’] = ’ci_sessions’;
: The Cookie driver has built-in garbage collection which clears out expired sessions so you do not need to write your
own routine to do it.
Native Driver
The Native driver relies on native PHP sessions to store data in the $_SESSION superglobal array. All stored values
continue to be available through $_SESSION, but flash- and temp- data items carry special prefixes.
Custom Drivers
You may also create your own custom session drivers. A session driver basically manages an array of name/value
pairs with some sort of storage mechanism.
To make a new driver, extend CI_Session_driver. Overload the initialize() method and read or create session data.
Then implement a save handler to write changed data to storage (sess_save), a destroy handler to remove deleted data
(sess_destroy), a regenerate handler to make a new session ID (sess_regenerate), and an access handler to expose the
data (get_userdata). Your initial class might look like:
class CI_Session_custom extends CI_Session_driver {
protected function initialize()
{
// Read existing session data or create a new one
}
public function sess_save()
{
// Save current data to storage
}
7.1. Libraries
165
CodeIgniter Documentation, 3.0-dev
public function sess_destroy()
{
// Destroy the current session and clean up storage
}
public function sess_regenerate()
{
// Create new session ID
}
public function &get_userdata()
{
// Return a reference to your userdata array
}
}
Notice that get_userdata() returns a reference so the parent library is accessing the same array the driver object is
using. This saves memory and avoids synchronization issues during usage.
Put your driver in the libraries/Session/drivers folder anywhere in your package paths. This includes the application
directory, the system directory, or any path you add with $CI->load->add_package_path(). Your driver must be named
CI_Session_<name>, and your filename must be Session_<name>.php, preferably also capitalized, such as:
CI_Session_foo in libraries/Session/drivers/Session_foo.php
Then specify the driver by setting ‘sess_driver’ in your config.php file or as a parameter when loading the CI_Session
object:
$config[’sess_driver’] = ’foo’;
OR:
$CI->load->driver(’session’, array(’sess_driver’ => ’foo’));
The driver specified by ‘sess_driver’ is automatically included as a valid driver. However, if you want to make a custom
driver available as an option without making it the initially loaded driver, set ‘sess_valid_drivers’ in your config.php
file to an array including your driver name:
$config[’sess_valid_drivers’] = array(’sess_driver’);
7.1.22 HTML Table Class
The Table Class provides functions that enable you to auto-generate HTML tables from arrays or database result sets.
Initializing the Class
Like most other classes in CodeIgniter, the Table class is initialized in your controller using the $this->load->library
function:
$this->load->library(’table’);
Once loaded, the Table library object will be available using: $this->table
166
Chapter 7.
CodeIgniter Documentation, 3.0-dev
Examples
Here is an example showing how you can create a table from a multi-dimensional array. Note that the first array index
will become the table heading (or you can set your own headings using the set_heading() function described in the
function reference below).
$this->load->library(’table’);
$data = array(
array(’Name’,
array(’Fred’,
array(’Mary’,
array(’John’,
);
’Color’, ’Size’),
’Blue’, ’Small’),
’Red’, ’Large’),
’Green’, ’Medium’)
echo $this->table->generate($data);
Here is an example of a table created from a database query result. The table class will automatically generate the
headings based on the table names (or you can set your own headings using the set_heading() function described in
the function reference below).
$this->load->library(’table’);
$query = $this->db->query("SELECT * FROM my_table");
echo $this->table->generate($query);
Here is an example showing how you might create a table using discrete parameters:
$this->load->library(’table’);
$this->table->set_heading(’Name’, ’Color’, ’Size’);
$this->table->add_row(’Fred’, ’Blue’, ’Small’);
$this->table->add_row(’Mary’, ’Red’, ’Large’);
$this->table->add_row(’John’, ’Green’, ’Medium’);
echo $this->table->generate();
Here is the same example, except instead of individual parameters, arrays are used:
$this->load->library(’table’);
$this->table->set_heading(array(’Name’, ’Color’, ’Size’));
$this->table->add_row(array(’Fred’, ’Blue’, ’Small’));
$this->table->add_row(array(’Mary’, ’Red’, ’Large’));
$this->table->add_row(array(’John’, ’Green’, ’Medium’));
echo $this->table->generate();
Changing the Look of Your Table
The Table Class permits you to set a table template with which you can specify the design of your layout. Here is the
template prototype:
$tmpl = array (
’table_open’
7.1. Libraries
=> ’<table border="0" cellpadding="4" cellspacing="0">’,
167
CodeIgniter Documentation, 3.0-dev
’heading_row_start’
’heading_row_end’
’heading_cell_start’
’heading_cell_end’
=>
=>
=>
=>
’<tr>’,
’</tr>’,
’<th>’,
’</th>’,
’row_start’
’row_end’
’cell_start’
’cell_end’
=>
=>
=>
=>
’<tr>’,
’</tr>’,
’<td>’,
’</td>’,
’row_alt_start’
’row_alt_end’
’cell_alt_start’
’cell_alt_end’
=>
=>
=>
=>
’<tr>’,
’</tr>’,
’<td>’,
’</td>’,
’table_close’
=> ’</table>’
);
$this->table->set_template($tmpl);
: You’ll notice there are two sets of “row” blocks in the template. These permit you to create alternating row colors
or design elements that alternate with each iteration of the row data.
You are NOT required to submit a complete template. If you only need to change parts of the layout you can simply
submit those elements. In this example, only the table opening tag is being changed:
$tmpl = array ( ’table_open’
=> ’<table border="1" cellpadding="2" cellspacing="1" class="mytable">’
$this->table->set_template($tmpl);
You can also set defaults for these in a config file.
Function Reference
$this->table->generate()
Returns a string containing the generated table. Accepts an optional parameter which can be an array or a database
result object.
$this->table->set_caption()
Permits you to add a caption to the table.
$this->table->set_caption(’Colors’);
$this->table->set_heading()
Permits you to set the table heading. You can submit an array or discrete params:
$this->table->set_heading(’Name’, ’Color’, ’Size’);
$this->table->set_heading(array(’Name’, ’Color’, ’Size’));
168
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->table->add_row()
Permits you to add a row to your table. You can submit an array or discrete params:
$this->table->add_row(’Blue’, ’Red’, ’Green’);
$this->table->add_row(array(’Blue’, ’Red’, ’Green’));
If you would like to set an individual cell’s tag attributes, you can use an associative array for that cell. The associative
key ‘data’ defines the cell’s data. Any other key => val pairs are added as key=’val’ attributes to the tag:
$cell = array(’data’ => ’Blue’, ’class’ => ’highlight’, ’colspan’ => 2);
$this->table->add_row($cell, ’Red’, ’Green’);
// generates
// <td class=’highlight’ colspan=’2’>Blue</td><td>Red</td><td>Green</td>
$this->table->make_columns()
This function takes a one-dimensional array as input and creates a multi-dimensional array with a depth equal to the
number of columns desired. This allows a single array with many elements to be displayed in a table that has a fixed
column count. Consider this example:
$list = array(’one’, ’two’, ’three’, ’four’, ’five’, ’six’, ’seven’, ’eight’, ’nine’, ’ten’, ’eleven’
$new_list = $this->table->make_columns($list, 3);
$this->table->generate($new_list);
// Generates a table with this prototype
<table border="0" cellpadding="4" cellspacing="0">
<tr>
<td>one</td><td>two</td><td>three</td>
</tr><tr>
<td>four</td><td>five</td><td>six</td>
</tr><tr>
<td>seven</td><td>eight</td><td>nine</td>
</tr><tr>
<td>ten</td><td>eleven</td><td>twelve</td></tr>
</table>
$this->table->set_template()
Permits you to set your template. You can submit a full or partial template.
$tmpl = array ( ’table_open’
=> ’<table border="1" cellpadding="2" cellspacing="1" class="mytable">’
$this->table->set_template($tmpl);
$this->table->set_empty()
Let’s you set a default value for use in any table cells that are empty. You might, for example, set a non-breaking
space:
7.1. Libraries
169
CodeIgniter Documentation, 3.0-dev
$this->table->set_empty("&nbsp;");
$this->table->clear()
Lets you clear the table heading and row data. If you need to show multiple tables with different data you should to
call this function after each table has been generated to empty the previous table information. Example:
$this->load->library(’table’);
$this->table->set_heading(’Name’, ’Color’, ’Size’);
$this->table->add_row(’Fred’, ’Blue’, ’Small’);
$this->table->add_row(’Mary’, ’Red’, ’Large’);
$this->table->add_row(’John’, ’Green’, ’Medium’);
echo $this->table->generate();
$this->table->clear();
$this->table->set_heading(’Name’, ’Day’, ’Delivery’);
$this->table->add_row(’Fred’, ’Wednesday’, ’Express’);
$this->table->add_row(’Mary’, ’Monday’, ’Air’);
$this->table->add_row(’John’, ’Saturday’, ’Overnight’);
echo $this->table->generate();
$this->table->function
Allows you to specify a native PHP function or a valid function array object to be applied to all cell data.
$this->load->library(’table’);
$this->table->set_heading(’Name’, ’Color’, ’Size’);
$this->table->add_row(’Fred’, ’<strong>Blue</strong>’, ’Small’);
$this->table->function = ’htmlspecialchars’;
echo $this->table->generate();
In the above example, all cell data would be ran through PHP’s htmlspecialchars() function, resulting in:
<td>Fred</td><td>&lt;strong&gt;Blue&lt;/strong&gt;</td><td>Small</td>
7.1.23 Trackback Class
The Trackback Class provides functions that enable you to send and receive Trackback data.
If you are not familiar with Trackbacks you’ll find more information here.
Initializing the Class
Like most other classes in CodeIgniter, the Trackback class is initialized in your controller using the $this->load>library function:
170
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->load->library(’trackback’);
Once loaded, the Trackback library object will be available using: $this->trackback
Sending Trackbacks
A Trackback can be sent from any of your controller functions using code similar to this example:
$this->load->library(’trackback’);
$tb_data = array(
’ping_url’
’url’
’title’
’excerpt’
’blog_name’
’charset’
);
=>
=>
=>
=>
=>
=>
’http://example.com/trackback/456’,
’http://www.my-example.com/blog/entry/123’,
’The Title of My Entry’,
’The entry content.’,
’My Blog Name’,
’utf-8’
if ( ! $this->trackback->send($tb_data))
{
echo $this->trackback->display_errors();
}
else
{
echo ’Trackback was sent!’;
}
Description of array data:
• ping_url - The URL of the site you are sending the Trackback to. You can send Trackbacks to multiple URLs
by separating each URL with a comma.
• url - The URL to YOUR site where the weblog entry can be seen.
• title - The title of your weblog entry.
• excerpt - The content of your weblog entry. Note: the Trackback class will automatically send only the first 500
characters of your entry. It will also strip all HTML.
• blog_name - The name of your weblog.
• charset - The character encoding your weblog is written in. If omitted, UTF-8 will be used.
The Trackback sending function returns TRUE/FALSE (boolean) on success or failure. If it fails, you can retrieve the
error message using:
$this->trackback->display_errors();
Receiving Trackbacks
Before you can receive Trackbacks you must create a weblog. If you don’t have a blog yet there’s no point in continuing.
Receiving Trackbacks is a little more complex than sending them, only because you will need a database table in
which to store them, and you will need to validate the incoming trackback data. You are encouraged to implement
a thorough validation process to guard against spam and duplicate data. You may also want to limit the number of
Trackbacks you allow from a particular IP within a given span of time to further curtail spam. The process of receiving
a Trackback is quite simple; the validation is what takes most of the effort.
7.1. Libraries
171
CodeIgniter Documentation, 3.0-dev
Your Ping URL
In order to accept Trackbacks you must display a Trackback URL next to each one of your weblog entries. This will
be the URL that people will use to send you Trackbacks (we will refer to this as your “Ping URL”).
Your Ping URL must point to a controller function where your Trackback receiving code is located, and the URL must
contain the ID number for each particular entry, so that when the Trackback is received you’ll be able to associate it
with a particular entry.
For example, if your controller class is called Trackback, and the receiving function is called receive, your Ping URLs
will look something like this:
http://example.com/index.php/trackback/receive/entry_id
Where entry_id represents the individual ID number for each of your entries.
Creating a Trackback Table
Before you can receive Trackbacks you must create a table in which to store them. Here is a basic prototype for such
a table:
CREATE TABLE trackbacks (
tb_id int(10) unsigned NOT NULL auto_increment,
entry_id int(10) unsigned NOT NULL default 0,
url varchar(200) NOT NULL,
title varchar(100) NOT NULL,
excerpt text NOT NULL,
blog_name varchar(100) NOT NULL,
tb_date int(10) NOT NULL,
ip_address varchar(45) NOT NULL,
PRIMARY KEY ‘tb_id‘ (‘tb_id‘),
KEY ‘entry_id‘ (‘entry_id‘)
);
The Trackback specification only requires four pieces of information to be sent in a Trackback (url, title, excerpt,
blog_name), but to make the data more useful we’ve added a few more fields in the above table schema (date, IP
address, etc.).
Processing a Trackback
Here is an example showing how you will receive and process a Trackback. The following code is intended for use
within the controller function where you expect to receive Trackbacks.
$this->load->library(’trackback’);
$this->load->database();
if ($this->uri->segment(3) == FALSE)
{
$this->trackback->send_error("Unable to determine the entry ID");
}
if ( ! $this->trackback->receive())
{
$this->trackback->send_error("The Trackback did not contain valid data");
}
$data = array(
172
Chapter 7.
CodeIgniter Documentation, 3.0-dev
’tb_id’
’entry_id’
’url’
’title’
’excerpt’
’blog_name’
’tb_date’
’ip_address’
);
=>
=>
=>
=>
=>
=>
=>
=>
’’,
$this->uri->segment(3),
$this->trackback->data(’url’),
$this->trackback->data(’title’),
$this->trackback->data(’excerpt’),
$this->trackback->data(’blog_name’),
time(),
$this->input->ip_address()
$sql = $this->db->insert_string(’trackbacks’, $data);
$this->db->query($sql);
$this->trackback->send_success();
Notes:
The entry ID number is expected in the third segment of your URL. This is based on the URI example we gave earlier:
http://example.com/index.php/trackback/receive/entry_id
Notice the entry_id is in the third URI segment, which you can retrieve using:
$this->uri->segment(3);
In our Trackback receiving code above, if the third segment is missing, we will issue an error. Without a valid entry
ID, there’s no reason to continue.
The $this->trackback->receive() function is simply a validation function that looks at the incoming data and makes
sure it contains the four pieces of data that are required (url, title, excerpt, blog_name). It returns TRUE on success
and FALSE on failure. If it fails you will issue an error message.
The incoming Trackback data can be retrieved using this function:
$this->trackback->data(’item’)
Where item represents one of these four pieces of info: url, title, excerpt, or blog_name
If the Trackback data is successfully received, you will issue a success message using:
$this->trackback->send_success();
: The above code contains no data validation, which you are encouraged to add.
7.1.24 Typography Class
The Typography Class provides functions that help you format text.
Initializing the Class
Like most other classes in CodeIgniter, the Typography class is initialized in your controller using the $this->load>library function:
$this->load->library(’typography’);
Once loaded, the Typography library object will be available using: $this->typography
7.1. Libraries
173
CodeIgniter Documentation, 3.0-dev
auto_typography()
Formats text so that it is semantically and typographically correct HTML. Takes a string as input and returns it with
the following formatting:
• Surrounds paragraphs within <p></p> (looks for double line breaks to identify paragraphs).
• Single line breaks are converted to <br />, except those that appear within <pre> tags.
• Block level elements, like <div> tags, are not wrapped within paragraphs, but their contained text is if it contains
paragraphs.
• Quotes are converted to correctly facing curly quote entities, except those that appear within tags.
• Apostrophes are converted to curly apostrophe entities.
• Double dashes (either like – this or like–this) are converted to em—dashes.
• Three consecutive periods either preceding or following a word are converted to ellipsis. . .
• Double spaces following sentences are converted to non-breaking spaces to mimic double spacing.
Usage example:
$string = $this->typography->auto_typography($string);
Parameters
There is one optional parameters that determines whether the parser should reduce more then two consecutive line
breaks down to two. Use boolean TRUE or FALSE.
By default the parser does not reduce line breaks. In other words, if no parameters are submitted, it is the same as
doing this:
$string = $this->typography->auto_typography($string, FALSE);
: Typographic formatting can be processor intensive, particularly if you have a lot of content being formatted. If you
choose to use this function you may want to consider caching your pages.
format_characters()
This function is similar to the auto_typography function above, except that it only does character conversion:
• Quotes are converted to correctly facing curly quote entities, except those that appear within tags.
• Apostrophes are converted to curly apostrophe entities.
• Double dashes (either like – this or like–this) are converted to em—dashes.
• Three consecutive periods either preceding or following a word are converted to ellipsis. . .
• Double spaces following sentences are converted to non-breaking spaces to mimic double spacing.
Usage example:
$string = $this->typography->format_characters($string);
174
Chapter 7.
CodeIgniter Documentation, 3.0-dev
nl2br_except_pre()
Converts newlines to <br /> tags unless they appear within <pre> tags. This function is identical to the native PHP
nl2br() function, except that it ignores <pre> tags.
Usage example:
$string = $this->typography->nl2br_except_pre($string);
protect_braced_quotes
When using the Typography library in conjunction with the Template Parser library it can often be desirable to protect
single and double quotes within curly braces. To enable this, set the protect_braced_quotes class property to TRUE.
Usage example:
$this->load->library(’typography’);
$this->typography->protect_braced_quotes = TRUE;
7.1.25 Unit Testing Class
Unit testing is an approach to software development in which tests are written for each function in your application. If
you are not familiar with the concept you might do a little googling on the subject.
CodeIgniter’s Unit Test class is quite simple, consisting of an evaluation function and two result functions. It’s not
intended to be a full-blown test suite but rather a simple mechanism to evaluate your code to determine if it is producing
the correct data type and result.
Initializing the Class
Like most other classes in CodeIgniter, the Unit Test class is initialized in your controller using the $this->load->library
function:
$this->load->library(’unit_test’);
Once loaded, the Unit Test object will be available using: $this->unit
Running Tests
Running a test involves supplying a test and an expected result to the following function:
$this->unit->run( test, expected result, ‘test name’, ‘notes’);
Where test is the result of the code you wish to test, expected result is the data type you expect, test name is an optional
name you can give your test, and notes are optional notes. Example:
$test = 1 + 1;
$expected_result = 2;
$test_name = ’Adds one plus one’;
$this->unit->run($test, $expected_result, $test_name);
7.1. Libraries
175
CodeIgniter Documentation, 3.0-dev
The expected result you supply can either be a literal match, or a data type match. Here’s an example of a literal:
$this->unit->run(’Foo’, ’Foo’);
Here is an example of a data type match:
$this->unit->run(’Foo’, ’is_string’);
Notice the use of “is_string” in the second parameter? This tells the function to evaluate whether your test is producing
a string as the result. Here is a list of allowed comparison types:
• is_object
• is_string
• is_bool
• is_true
• is_false
• is_int
• is_numeric
• is_float
• is_double
• is_array
• is_null
Generating Reports
You can either display results after each test, or your can run several tests and generate a report at the end. To show a
report directly simply echo or return the run function:
echo $this->unit->run($test, $expected_result);
To run a full report of all tests, use this:
echo $this->unit->report();
The report will be formatted in an HTML table for viewing. If you prefer the raw data you can retrieve an array using:
echo $this->unit->result();
Strict Mode
By default the unit test class evaluates literal matches loosely. Consider this example:
$this->unit->run(1, TRUE);
The test is evaluating an integer, but the expected result is a boolean. PHP, however, due to it’s loose data-typing will
evaluate the above code as TRUE using a normal equality test:
if (1 == TRUE) echo ’This evaluates as true’;
If you prefer, you can put the unit test class in to strict mode, which will compare the data type as well as the value:
176
Chapter 7.
CodeIgniter Documentation, 3.0-dev
if (1 === TRUE) echo ’This evaluates as FALSE’;
To enable strict mode use this:
$this->unit->use_strict(TRUE);
Enabling/Disabling Unit Testing
If you would like to leave some testing in place in your scripts, but not have it run unless you need it, you can disable
unit testing using:
$this->unit->active(FALSE)
Unit Test Display
When your unit test results display, the following items show by default:
• Test Name (test_name)
• Test Datatype (test_datatype)
• Expected Datatype (res_datatype)
• Result (result)
• File Name (file)
• Line Number (line)
• Any notes you entered for the test (notes)
You can customize which of these items get displayed by using $this->unit->set_test_items(). For example, if you
only wanted the test name and the result displayed:
Customizing displayed tests
$this->unit->set_test_items(array(’test_name’, ’result’));
Creating a Template
If you would like your test results formatted differently then the default you can set your own template. Here is an
example of a simple template. Note the required pseudo-variables:
$str = ’
<table border="0" cellpadding="4" cellspacing="1">
{rows}
<tr>
<td>{item}</td>
<td>{result}</td>
</tr>
{/rows}
</table>’;
$this->unit->set_template($str);
7.1. Libraries
177
CodeIgniter Documentation, 3.0-dev
: Your template must be declared before running the unit test process.
7.1.26 URI Class
The URI Class provides functions that help you retrieve information from your URI strings. If you use URI routing,
you can also retrieve information about the re-routed segments.
: This class is initialized automatically by the system so there is no need to do it manually.
$this->uri->segment(n)
Permits you to retrieve a specific segment. Where n is the segment number you wish to retrieve. Segments are
numbered from left to right. For example, if your full URL is this:
http://example.com/index.php/news/local/metro/crime_is_up
The segment numbers would be this:
1. news
2. local
3. metro
4. crime_is_up
By default the function returns NULL if the segment does not exist. There is an optional second parameter that permits
you to set your own default value if the segment is missing. For example, this would tell the function to return the
number zero in the event of failure:
$product_id = $this->uri->segment(3, 0);
It helps avoid having to write code like this:
if ($this->uri->segment(3) === FALSE)
{
$product_id = 0;
}
else
{
$product_id = $this->uri->segment(3);
}
$this->uri->rsegment(n)
This function is identical to the previous one, except that it lets you retrieve a specific segment from your re-routed
URI in the event you are using CodeIgniter’s URI Routing feature.
$this->uri->slash_segment(n)
This function is almost identical to $this->uri->segment(), except it adds a trailing and/or leading slash based on the
second parameter. If the parameter is not used, a trailing slash added. Examples:
178
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->uri->slash_segment(3);
$this->uri->slash_segment(3, ’leading’);
$this->uri->slash_segment(3, ’both’);
Returns:
1. segment/
2. /segment
3. /segment/
$this->uri->slash_rsegment(n)
This function is identical to the previous one, except that it lets you add slashes a specific segment from your re-routed
URI in the event you are using CodeIgniter’s URI Routing feature.
$this->uri->uri_to_assoc(n)
This function lets you turn URI segments into and associative array of key/value pairs. Consider this URI:
index.php/user/search/name/joe/location/UK/gender/male
Using this function you can turn the URI into an associative array with this prototype:
[array]
(
’name’ => ’joe’
’location’ => ’UK’
’gender’
=> ’male’
)
The first parameter of the function lets you set an offset. By default it is set to 3 since your URI will normally contain
a controller/function in the first and second segments. Example:
$array = $this->uri->uri_to_assoc(3);
echo $array[’name’];
The second parameter lets you set default key names, so that the array returned by the function will always contain
expected indexes, even if missing from the URI. Example:
$default = array(’name’, ’gender’, ’location’, ’type’, ’sort’);
$array = $this->uri->uri_to_assoc(3, $default);
If the URI does not contain a value in your default, an array index will be set to that name, with a value of FALSE.
Lastly, if a corresponding value is not found for a given key (if there is an odd number of URI segments) the value will
be set to FALSE (boolean).
$this->uri->ruri_to_assoc(n)
This function is identical to the previous one, except that it creates an associative array using the re-routed URI in the
event you are using CodeIgniter’s URI Routing feature.
7.1. Libraries
179
CodeIgniter Documentation, 3.0-dev
$this->uri->assoc_to_uri()
Takes an associative array as input and generates a URI string from it. The array keys will be included in the string.
Example:
$array = array(’product’ => ’shoes’, ’size’ => ’large’, ’color’ => ’red’);
$str = $this->uri->assoc_to_uri($array);
// Produces: product/shoes/size/large/color/red
$this->uri->uri_string()
Returns a string with the complete URI. For example, if this is your full URL:
http://example.com/index.php/news/local/345
The function would return this:
news/local/345
$this->uri->ruri_string()
This function is identical to the previous one, except that it returns the re-routed URI in the event you are using
CodeIgniter’s URI Routing feature.
$this->uri->total_segments()
Returns the total number of segments.
$this->uri->total_rsegments()
This function is identical to the previous one, except that it returns the total number of segments in your re-routed URI
in the event you are using CodeIgniter’s URI Routing feature.
$this->uri->segment_array()
Returns an array containing the URI segments. For example:
$segs = $this->uri->segment_array();
foreach ($segs as $segment)
{
echo $segment;
echo ’<br />’;
}
$this->uri->rsegment_array()
This function is identical to the previous one, except that it returns the array of segments in your re-routed URI in the
event you are using CodeIgniter’s URI Routing feature.
180
Chapter 7.
CodeIgniter Documentation, 3.0-dev
7.1.27 User Agent Class
The User Agent Class provides functions that help identify information about the browser, mobile device, or robot
visiting your site. In addition you can get referrer information as well as language and supported character-set information.
Initializing the Class
Like most other classes in CodeIgniter, the User Agent class is initialized in your controller using the $this->load>library function:
$this->load->library(’user_agent’);
Once loaded, the object will be available using: $this->agent
User Agent Definitions
The user agent name definitions are located in a config file located at: application/config/user_agents.php. You may
add items to the various user agent arrays if needed.
Example
When the User Agent class is initialized it will attempt to determine whether the user agent browsing your site is a
web browser, a mobile device, or a robot. It will also gather the platform information if it is available.
$this->load->library(’user_agent’);
if ($this->agent->is_browser())
{
$agent = $this->agent->browser().’ ’.$this->agent->version();
}
elseif ($this->agent->is_robot())
{
$agent = $this->agent->robot();
}
elseif ($this->agent->is_mobile())
{
$agent = $this->agent->mobile();
}
else
{
$agent = ’Unidentified User Agent’;
}
echo $agent;
echo $this->agent->platform(); // Platform info (Windows, Linux, Mac, etc.)
Function Reference
$this->agent->is_browser()
Returns TRUE/FALSE (boolean) if the user agent is a known web browser.
7.1. Libraries
181
CodeIgniter Documentation, 3.0-dev
if ($this->agent->is_browser(’Safari’))
{
echo ’You are using Safari.’;
}
elseif ($this->agent->is_browser())
{
echo ’You are using a browser.’;
}
: The string “Safari” in this example is an array key in the list of browser definitions. You can find this list in
application/config/user_agents.php if you want to add new browsers or change the stings.
$this->agent->is_mobile()
Returns TRUE/FALSE (boolean) if the user agent is a known mobile device.
if ($this->agent->is_mobile(’iphone’))
{
$this->load->view(’iphone/home’);
}
elseif ($this->agent->is_mobile())
{
$this->load->view(’mobile/home’);
}
else
{
$this->load->view(’web/home’);
}
$this->agent->is_robot()
Returns TRUE/FALSE (boolean) if the user agent is a known robot.
: The user agent library only contains the most common robot definitions. It is not a complete list of bots. There are
hundreds of them so searching for each one would not be very efficient. If you find that some bots that commonly visit
your site are missing from the list you can add them to your application/config/user_agents.php file.
$this->agent->is_referral()
Returns TRUE/FALSE (boolean) if the user agent was referred from another site.
$this->agent->browser()
Returns a string containing the name of the web browser viewing your site.
$this->agent->version()
Returns a string containing the version number of the web browser viewing your site.
182
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->agent->mobile()
Returns a string containing the name of the mobile device viewing your site.
$this->agent->robot()
Returns a string containing the name of the robot viewing your site.
$this->agent->platform()
Returns a string containing the platform viewing your site (Linux, Windows, OS X, etc.).
$this->agent->referrer()
The referrer, if the user agent was referred from another site. Typically you’ll test for this as follows:
if ($this->agent->is_referral())
{
echo $this->agent->referrer();
}
$this->agent->agent_string()
Returns a string containing the full user agent string. Typically it will be something like this:
Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.0.4) Gecko/20060613 Camino/1.0.2
$this->agent->accept_lang()
Lets you determine if the user agent accepts a particular language. Example:
if ($this->agent->accept_lang(’en’))
{
echo ’You accept English!’;
}
: This function is not typically very reliable since some browsers do not provide language info, and even among those
that do, it is not always accurate.
$this->agent->accept_charset()
Lets you determine if the user agent accepts a particular character set. Example:
if ($this->agent->accept_charset(’utf-8’))
{
echo ’You browser supports UTF-8!’;
}
: This function is not typically very reliable since some browsers do not provide character-set info, and even among
those that do, it is not always accurate.
7.1. Libraries
183
CodeIgniter Documentation, 3.0-dev
7.1.28 XML-RPC and XML-RPC Server Classes
CodeIgniter’s XML-RPC classes permit you to send requests to another server, or set up your own XML-RPC server
to receive requests.
What is XML-RPC?
Quite simply it is a way for two computers to communicate over the internet using XML. One computer, which we
will call the client, sends an XML-RPC request to another computer, which we will call the server. Once the server
receives and processes the request it will send back a response to the client.
For example, using the MetaWeblog API, an XML-RPC Client (usually a desktop publishing tool) will send a request
to an XML-RPC Server running on your site. This request might be a new weblog entry being sent for publication, or
it could be a request for an existing entry for editing. When the XML-RPC Server receives this request it will examine
it to determine which class/method should be called to process the request. Once processed, the server will then send
back a response message.
For detailed specifications, you can visit the XML-RPC site.
Initializing the Class
Like most other classes in CodeIgniter, the XML-RPC and XML-RPCS classes are initialized in your controller using
the $this->load->library function:
To load the XML-RPC class you will use:
$this->load->library(’xmlrpc’);
Once loaded, the xml-rpc library object will be available using: $this->xmlrpc
To load the XML-RPC Server class you will use:
$this->load->library(’xmlrpc’);
$this->load->library(’xmlrpcs’);
Once loaded, the xml-rpcs library object will be available using: $this->xmlrpcs
: When using the XML-RPC Server class you must load BOTH the XML-RPC class and the XML-RPC Server class.
Sending XML-RPC Requests
To send a request to an XML-RPC server you must specify the following information:
• The URL of the server
• The method on the server you wish to call
• The request data (explained below).
Here is a basic example that sends a simple Weblogs.com ping to the Ping-o-Matic
$this->load->library(’xmlrpc’);
$this->xmlrpc->server(’http://rpc.pingomatic.com/’, 80);
$this->xmlrpc->method(’weblogUpdates.ping’);
$request = array(’My Photoblog’, ’http://www.my-site.com/photoblog/’);
184
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->xmlrpc->request($request);
if ( ! $this->xmlrpc->send_request())
{
echo $this->xmlrpc->display_error();
}
Explanation The above code initializes the XML-RPC class, sets the server URL and method to be called (weblogUpdates.ping). The request (in this case, the title and URL of your site) is placed into an array for transportation,
and compiled using the request() function. Lastly, the full request is sent. If the send_request() method returns false
we will display the error message sent back from the XML-RPC Server.
Anatomy of a Request
An XML-RPC request is simply the data you are sending to the XML-RPC server. Each piece of data in a request is
referred to as a request parameter. The above example has two parameters: The URL and title of your site. When the
XML-RPC server receives your request, it will look for parameters it requires.
Request parameters must be placed into an array for transportation, and each parameter can be one of seven data types
(strings, numbers, dates, etc.). If your parameters are something other than strings you will have to include the data
type in the request array.
Here is an example of a simple array with three parameters:
$request = array(’John’, ’Doe’, ’www.some-site.com’);
$this->xmlrpc->request($request);
If you use data types other than strings, or if you have several different data types, you will place each parameter into
its own array, with the data type in the second position:
$request = array (
array(’John’, ’string’),
array(’Doe’, ’string’),
array(FALSE, ’boolean’),
array(12345, ’int’)
);
$this->xmlrpc->request($request);
The Data Types section below has a full list of data types.
==========================
Creating an XML-RPC Server
An XML-RPC Server acts as a traffic cop of sorts, waiting for incoming requests and redirecting them to the appropriate functions for processing.
To create your own XML-RPC server involves initializing the XML-RPC Server class in your controller where you
expect the incoming request to appear, then setting up an array with mapping instructions so that incoming requests
can be sent to the appropriate class and method for processing.
Here is an example to illustrate:
$this->load->library(’xmlrpc’);
$this->load->library(’xmlrpcs’);
$config[’functions’][’new_post’] = array(’function’ => ’My_blog.new_entry’),
$config[’functions’][’update_post’] = array(’function’ => ’My_blog.update_entry’);
$config[’object’] = $this;
7.1. Libraries
185
CodeIgniter Documentation, 3.0-dev
$this->xmlrpcs->initialize($config);
$this->xmlrpcs->serve();
The above example contains an array specifying two method requests that the Server allows. The allowed methods
are on the left side of the array. When either of those are received, they will be mapped to the class and method on the
right.
The ‘object’ key is a special key that you pass an instantiated class object with, which is necessary when the method
you are mapping to is not part of the CodeIgniter super object.
In other words, if an XML-RPC Client sends a request for the new_post method, your server will load the My_blog
class and call the new_entry function. If the request is for the update_post method, your server will load the My_blog
class and call the update_entry function.
The function names in the above example are arbitrary. You’ll decide what they should be called on your server, or if
you are using standardized APIs, like the Blogger or MetaWeblog API, you’ll use their function names.
There are two additional configuration keys you may make use of when initializing the server class: debug can be
set to TRUE in order to enable debugging, and xss_clean may be set to FALSE to prevent sending data through the
Security library’s xss_clean function.
Processing Server Requests
When the XML-RPC Server receives a request and loads the class/method for processing, it will pass an object to that
method containing the data sent by the client.
Using the above example, if the new_post method is requested, the server will expect a class to exist with this prototype:
class My_blog extends CI_Controller {
public function new_post($request)
{
}
}
The $request variable is an object compiled by the Server, which contains the data sent by the XML-RPC Client.
Using this object you will have access to the request parameters enabling you to process the request. When you are
done you will send a Response back to the Client.
Below is a real-world example, using the Blogger API. One of the methods in the Blogger API is getUserInfo(). Using
this method, an XML-RPC Client can send the Server a username and password, in return the Server sends back
information about that particular user (nickname, user ID, email address, etc.). Here is how the processing function
might look:
class My_blog extends CI_Controller {
function getUserInfo($request)
{
$username = ’smitty’;
$password = ’secretsmittypass’;
$this->load->library(’xmlrpc’);
$parameters = $request->output_parameters();
if ($parameters[’1’] != $username AND $parameters[’2’] != $password)
186
Chapter 7.
CodeIgniter Documentation, 3.0-dev
{
return $this->xmlrpc->send_error_message(’100’, ’Invalid Access’);
}
$response = array(array(’nickname’
’userid’
’url’
’email’
’lastname’
’firstname’
),
’struct’);
=>
=>
=>
=>
=>
=>
array(’Smitty’,’string’),
array(’99’,’string’),
array(’http://yoursite.com’,’string’),
array(’jsmith@yoursite.com’,’string’),
array(’Smith’,’string’),
array(’John’,’string’)
return $this->xmlrpc->send_response($response);
}
}
Notes: The output_parameters() function retrieves an indexed array corresponding to the request parameters sent by
the client. In the above example, the output parameters will be the username and password.
If the username and password sent by the client were not valid, and error message is returned using
send_error_message().
If the operation was successful, the client will be sent back a response array containing the user’s info.
Formatting a Response
Similar to Requests, Responses must be formatted as an array. However, unlike requests, a response is an array that
contains a single item. This item can be an array with several additional arrays, but there can be only one primary
array index. In other words, the basic prototype is this:
$response = array(’Response data’,
’array’);
Responses, however, usually contain multiple pieces of information. In order to accomplish this we must put the
response into its own array so that the primary array continues to contain a single piece of data. Here’s an example
showing how this might be accomplished:
$response = array (
array(
’first_name’ => array(’John’, ’string’),
’last_name’ => array(’Doe’, ’string’),
’member_id’ => array(123435, ’int’),
’todo_list’ => array(array(’clean house’, ’call mom’, ’water plants’), ’arra
),
’struct’
);
Notice that the above array is formatted as a struct. This is the most common data type for responses.
As with Requests, a response can be one of the seven data types listed in the Data Types section.
Sending an Error Response
If you need to send the client an error response you will use the following:
7.1. Libraries
187
CodeIgniter Documentation, 3.0-dev
return $this->xmlrpc->send_error_message(’123’, ’Requested data not available’);
The first parameter is the error number while the second parameter is the error message.
Creating Your Own Client and Server
To help you understand everything we’ve covered thus far, let’s create a couple controllers that act as XML-RPC Client
and Server. You’ll use the Client to send a request to the Server and receive a response.
The Client Using a text editor, create a controller called Xmlrpc_client.php. In it, place this code and save it to your
application/controllers/ folder:
<?php
class Xmlrpc_client extends CI_Controller {
public function index()
{
$this->load->helper(’url’);
$server_url = site_url(’xmlrpc_server’);
$this->load->library(’xmlrpc’);
$this->xmlrpc->server($server_url, 80);
$this->xmlrpc->method(’Greetings’);
$request = array(’How is it going?’);
$this->xmlrpc->request($request);
if ( ! $this->xmlrpc->send_request())
{
echo $this->xmlrpc->display_error();
}
else
{
echo ’<pre>’;
print_r($this->xmlrpc->display_response());
echo ’</pre>’;
}
}
}
?>
: In the above code we are using a “url helper”. You can find more information in the Helpers Functions page.
The Server Using a text editor, create a controller called Xmlrpc_server.php. In it, place this code and save it to
your application/controllers/ folder:
<?php
class Xmlrpc_server extends CI_Controller {
public function index()
{
188
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->load->library(’xmlrpc’);
$this->load->library(’xmlrpcs’);
$config[’functions’][’Greetings’] = array(’function’ => ’Xmlrpc_server.process’);
$this->xmlrpcs->initialize($config);
$this->xmlrpcs->serve();
}
public function process($request)
{
$parameters = $request->output_parameters();
$response = array(
array(
’you_said’ => $parameters[0],
’i_respond’ => ’Not bad at all.’
),
’struct’
);
return $this->xmlrpc->send_response($response);
}
}
?>
Try it! Now visit the your site using a URL similar to this:
example.com/index.php/xmlrpc_client/
You should now see the message you sent to the server, and its response back to you.
The client you created sends a message (“How’s is going?”) to the server, along with a request for the “Greetings”
method. The Server receives the request and maps it to the “process” function, where a response is sent back.
Using Associative Arrays In a Request Parameter
If you wish to use an associative array in your method parameters you will need to use a struct datatype:
$request = array(
array(
// Param 0
array(
’name’=>’John’
),
’struct’
),
array(
// Param 1
array(
’size’=>’large’,
’shape’=>’round’
),
’struct’
)
7.1. Libraries
189
CodeIgniter Documentation, 3.0-dev
);
$this->xmlrpc->request($request);
You can retrieve the associative array when processing the request in the Server.
$parameters = $request->output_parameters();
$name = $parameters[0][’name’];
$size = $parameters[1][’size’];
$shape = $parameters[1][’shape’];
XML-RPC Function Reference
$this->xmlrpc->server()
Sets the URL and port number of the server to which a request is to be sent:
$this->xmlrpc->server(’http://www.sometimes.com/pings.php’, 80);
$this->xmlrpc->timeout()
Set a time out period (in seconds) after which the request will be canceled:
$this->xmlrpc->timeout(6);
$this->xmlrpc->method()
Sets the method that will be requested from the XML-RPC server:
$this->xmlrpc->method(’method’);
Where method is the name of the method.
$this->xmlrpc->request()
Takes an array of data and builds request to be sent to XML-RPC server:
$request = array(array(’My Photoblog’, ’string’), ’http://www.yoursite.com/photoblog/’);
$this->xmlrpc->request($request);
$this->xmlrpc->send_request()
The request sending function. Returns boolean TRUE or FALSE based on success for failure, enabling it to be used
conditionally.
$this->xmlrpc->set_debug(TRUE);
Enables debugging, which will display a variety of information and error data helpful during development.
190
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$this->xmlrpc->display_error()
Returns an error message as a string if your request failed for some reason.
echo $this->xmlrpc->display_error();
$this->xmlrpc->display_response()
Returns the response from the remote server once request is received. The response will typically be an associative
array.
$this->xmlrpc->display_response();
$this->xmlrpc->send_error_message()
This function lets you send an error message from your server to the client. First parameter is the error number while
the second parameter is the error message.
return $this->xmlrpc->send_error_message(’123’, ’Requested data not available’);
$this->xmlrpc->send_response()
Lets you send the response from your server to the client. An array of valid data values must be sent with this method.
$response = array(
array(
’flerror’ => array(FALSE, ’boolean’),
’message’ => "Thanks for the ping!"
)
’struct’);
return $this->xmlrpc->send_response($response);
Data Types
According to the XML-RPC spec there are seven types of values that you can send via XML-RPC:
• int or i4
• boolean
• string
• double
• dateTime.iso8601
• base64
• struct (contains array of values)
• array (contains array of values)
7.1. Libraries
191
CodeIgniter Documentation, 3.0-dev
7.1.29 Zip Encoding Class
CodeIgniter’s Zip Encoding Class classes permit you to create Zip archives. Archives can be downloaded to your
desktop or saved to a directory.
Initializing the Class
Like most other classes in CodeIgniter, the Zip class is initialized in your controller using the $this->load->library
function:
$this->load->library(’zip’);
Once loaded, the Zip library object will be available using: $this->zip
Usage Example
This example demonstrates how to compress a file, save it to a folder on your server, and download it to your desktop.
$name = ’mydata1.txt’;
$data = ’A Data String!’;
$this->zip->add_data($name, $data);
// Write the zip file to a folder on your server. Name it "my_backup.zip"
$this->zip->archive(’/path/to/directory/my_backup.zip’);
// Download the file to your desktop. Name it "my_backup.zip"
$this->zip->download(’my_backup.zip’);
Function Reference
$this->zip->add_data()
Permits you to add data to the Zip archive. The first parameter must contain the name you would like given to the file,
the second parameter must contain the file data as a string:
$name = ’my_bio.txt’;
$data = ’I was born in an elevator...’;
$this->zip->add_data($name, $data);
You are allowed multiple calls to this function in order to add several files to your archive. Example:
$name = ’mydata1.txt’;
$data = ’A Data String!’;
$this->zip->add_data($name, $data);
$name = ’mydata2.txt’;
$data = ’Another Data String!’;
$this->zip->add_data($name, $data);
Or you can pass multiple files using an array:
192
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$data = array(
’mydata1.txt’ => ’A Data String!’,
’mydata2.txt’ => ’Another Data String!’
);
$this->zip->add_data($data);
$this->zip->download(’my_backup.zip’);
If you would like your compressed data organized into sub-folders, include the path as part of the filename:
$name = ’personal/my_bio.txt’;
$data = ’I was born in an elevator...’;
$this->zip->add_data($name, $data);
The above example will place my_bio.txt inside a folder called personal.
$this->zip->add_dir()
Permits you to add a directory. Usually this function is unnecessary since you can place your data into folders when
using $this->zip->add_data(), but if you would like to create an empty folder you can do so. Example:
$this->zip->add_dir(’myfolder’); // Creates a folder called "myfolder"
$this->zip->read_file()
Permits you to compress a file that already exists somewhere on your server. Supply a file path and the zip class will
read it and add it to the archive:
$path = ’/path/to/photo.jpg’;
$this->zip->read_file($path);
// Download the file to your desktop. Name it "my_backup.zip"
$this->zip->download(’my_backup.zip’);
If you would like the Zip archive to maintain the directory structure of the file in it, pass TRUE (boolean) in the second
parameter. Example:
$path = ’/path/to/photo.jpg’;
$this->zip->read_file($path, TRUE);
// Download the file to your desktop. Name it "my_backup.zip"
$this->zip->download(’my_backup.zip’);
In the above example, photo.jpg will be placed inside two folders: path/to/
$this->zip->read_dir()
Permits you to compress a folder (and its contents) that already exists somewhere on your server. Supply a file path
to the directory and the zip class will recursively read it and recreate it as a Zip archive. All files contained within the
supplied path will be encoded, as will any sub-folders contained within it. Example:
7.1. Libraries
193
CodeIgniter Documentation, 3.0-dev
$path = ’/path/to/your/directory/’;
$this->zip->read_dir($path);
// Download the file to your desktop. Name it "my_backup.zip"
$this->zip->download(’my_backup.zip’);
By default the Zip archive will place all directories listed in the first parameter inside the zip. If you want the tree
preceding the target folder to be ignored you can pass FALSE (boolean) in the second parameter. Example:
$path = ’/path/to/your/directory/’;
$this->zip->read_dir($path, FALSE);
This will create a ZIP with the folder “directory” inside, then all sub-folders stored correctly inside that, but will not
include the folders /path/to/your.
$this->zip->archive()
Writes the Zip-encoded file to a directory on your server. Submit a valid server path ending in the file name. Make
sure the directory is writable (666 or 777 is usually OK). Example:
$this->zip->archive(’/path/to/folder/myarchive.zip’); // Creates a file named myarchive.zip
$this->zip->download()
Causes the Zip file to be downloaded from your server. The function must be passed the name you would like the zip
file called. Example:
$this->zip->download(’latest_stuff.zip’); // File will be named "latest_stuff.zip"
: Do not display any data in the controller in which you call this function since it sends various server headers that
cause the download to happen and the file to be treated as binary.
$this->zip->get_zip()
Returns the Zip-compressed file data. Generally you will not need this function unless you want to do something
unique with the data. Example:
$name = ’my_bio.txt’;
$data = ’I was born in an elevator...’;
$this->zip->add_data($name, $data);
$zip_file = $this->zip->get_zip();
$this->zip->clear_data()
The Zip class caches your zip data so that it doesn’t need to recompile the Zip archive for each function you use
above. If, however, you need to create multiple Zips, each with different data, you can clear the cache between calls.
Example:
194
Chapter 7.
CodeIgniter Documentation, 3.0-dev
$name = ’my_bio.txt’;
$data = ’I was born in an elevator...’;
$this->zip->add_data($name, $data);
$zip_file = $this->zip->get_zip();
$this->zip->clear_data();
$name = ’photo.jpg’;
$this->zip->read_file("/path/to/photo.jpg"); // Read the file’s contents
$this->zip->download(’myphotos.zip’);
7.1. Libraries
195
CodeIgniter Documentation, 3.0-dev
196
Chapter 7.
CHAPTER 8
Driver
• Caching Driver
• The Database Class
• Javascript Class
• Session Driver
197
CodeIgniter Documentation, 3.0-dev
198
Chapter 8. Driver
CHAPTER 9
9.1 Helpers
9.1.1 Array Helper
The Array Helper file contains functions that assist in working with arrays.
Page Contents
• Array Helper
– Loading this Helper
– element()
– elements()
– random_element()
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’array’);
The following functions are available:
element()
element($item, $array, $default = NULL)
• $item (string) – Item to fetch from the array
• $array (array) – Input array
• $default (bool) – What to return if the array isn’t valid
NULL on failure or the array item.
Lets you fetch an item from an array. The function tests whether the array index is set and whether it has a value. If a
value exists it is returned. If a value does not exist it returns NULL, or whatever you’ve specified as the default value
via the third parameter.
199
CodeIgniter Documentation, 3.0-dev
Example:
$array = array(
’color’ => ’red’,
’shape’ => ’round’,
’size’ => ’’
);
echo element(’color’, $array); // returns "red"
echo element(’size’, $array, ’foobar’); // returns "foobar"
elements()
elements($items, $array, $default = NULL)
• $item (string) – Item to fetch from the array
• $array (array) – Input array
• $default (bool) – What to return if the array isn’t valid
NULL on failure or the array item.
Lets you fetch a number of items from an array. The function tests whether each of the array indices is set. If an index
does not exist it is set to NULL, or whatever you’ve specified as the default value via the third parameter.
Example:
$array = array(
’color’ => ’red’,
’shape’ => ’round’,
’radius’ => ’10’,
’diameter’ => ’20’
);
$my_shape = elements(array(’color’, ’shape’, ’height’), $array);
The above will return the following array:
array(
’color’ => ’red’,
’shape’ => ’round’,
’height’ => NULL
);
You can set the third parameter to any default value you like.
$my_shape = elements(array(’color’, ’shape’, ’height’), $array, ’foobar’);
The above will return the following array:
array(
’color’
’shape’
’height’
=> ’red’,
=> ’round’,
=> ’foobar’
);
This is useful when sending the $_POST array to one of your Models. This prevents users from sending additional
POST data to be entered into your tables.
200
Chapter 9.
CodeIgniter Documentation, 3.0-dev
$this->load->model(’post_model’);
$this->post_model->update(
elements(array(’id’, ’title’, ’content’), $_POST)
);
This ensures that only the id, title and content fields are sent to be updated.
random_element()
random_element($array)
• $array (array) – Input array
string (a random element from the array)
Takes an array as input and returns a random element from it.
Usage example:
$quotes = array(
"I find that the harder I work, the more luck I seem to have. - Thomas Jefferson",
"Don’t stay in bed, unless you can make money in bed. - George Burns",
"We didn’t lose the game; we just ran out of time. - Vince Lombardi",
"If everything seems under control, you’re not going fast enough. - Mario Andretti",
"Reality is merely an illusion, albeit a very persistent one. - Albert Einstein",
"Chance favors the prepared mind - Louis Pasteur"
);
echo random_element($quotes);
9.1.2 CAPTCHA Helper
The CAPTCHA Helper file contains functions that assist in creating CAPTCHA images.
Page Contents
• CAPTCHA Helper
– Loading this Helper
– create_captcha()
* Using the CAPTCHA helper
* Adding a Database
Loading this Helper
This helper is loaded using the following code
$this->load->helper(’captcha’);
The following functions are available:
9.1. Helpers
201
CodeIgniter Documentation, 3.0-dev
create_captcha()
function create_captcha($data = ’’, $img_path = ’’, $img_url = ’’, $font_path = ’’)
• $data (array) – Array of data for the CAPTCHA
• $img_path (string) – Path to create the image in
• $img_url (string) – URL to the CAPTCHA image folder
• $font_path (string) – Server path to font
array
Takes an array of information to generate the CAPTCHA as input and creates the image to your specifications, returning an array of associative data about the image.
array(
’word’
’time’
’image’
’filename’
=>
=>
=>
=>
CAPTCHA WORD,
TIMESTAMP (in microtime),
IMAGE TAG,
IMAGE FILE NAME
)
The image is the actual image tag:
<img src="http://example.com/captcha/12345.jpg" width="140" height="50" />
The time is the micro timestamp used as the image name without the file extension. It will be a number like this:
1139612155.3422
The word is the word that appears in the captcha image, which if not supplied to the function, will be a random string.
Using the CAPTCHA helper
Once loaded you can generate a captcha like this:
$vals = array(
’word’
’img_path’
’img_url’
’font_path’
’img_width’
’img_height’
’expiration’
’word_length’
’pool’
=>
=>
=>
=>
=>
=>
=>
=>
=>
’Random word’,
’./captcha/’,
’http://example.com/captcha/’,
’./path/to/fonts/texb.ttf’,
’150’,
30,
7200,
8,
’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’,
// White background and border, black text and red grid
’colors’
=> array(
’background’ => array(255, 255, 255),
’border’ => array(255, 255, 255),
’text’ => array(0, 0, 0),
’grid’ => array(255, 40, 40)
)
);
$cap = create_captcha($vals);
echo $cap[’image’];
202
Chapter 9.
CodeIgniter Documentation, 3.0-dev
• The captcha function requires the GD image library.
• Only the img_path and img_url are required.
• If a word is not supplied, the function will generate a random ASCII string. You might put together your own
word library that you can draw randomly from.
• If you do not specify a path to a TRUE TYPE font, the native ugly GD font will be used.
• The “captcha” folder must be writable (666, or 777)
• The expiration (in seconds) signifies how long an image will remain in the captcha folder before it will be
deleted. The default is two hours.
• word_length defaults to 8, pool defaults to ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’
• If any of the colors values is missing, it will be replaced by the default.
Adding a Database
In order for the captcha function to prevent someone from submitting, you will need to add the information returned
from create_captcha() to your database. Then, when the data from the form is submitted by the user you will
need to verify that the data exists in the database and has not expired.
Here is a table prototype:
CREATE TABLE captcha (
captcha_id bigint(13) unsigned NOT NULL auto_increment,
captcha_time int(10) unsigned NOT NULL,
ip_address varchar(45) NOT NULL,
word varchar(20) NOT NULL,
PRIMARY KEY ‘captcha_id‘ (‘captcha_id‘),
KEY ‘word‘ (‘word‘)
);
Here is an example of usage with a database. On the page where the CAPTCHA will be shown you’ll have something
like this:
$this->load->helper(’captcha’);
$vals = array(
’img_path’
=> ’./captcha/’,
’img_url’
=> ’http://example.com/captcha/’
);
$cap = create_captcha($vals);
$data = array(
’captcha_time’ => $cap[’time’],
’ip_address’
=> $this->input->ip_address(),
’word’
=> $cap[’word’]
);
$query = $this->db->insert_string(’captcha’, $data);
$this->db->query($query);
echo ’Submit the word you see below:’;
echo $cap[’image’];
echo ’<input type="text" name="captcha" value="" />’;
Then, on the page that accepts the submission you’ll have something like this:
9.1. Helpers
203
CodeIgniter Documentation, 3.0-dev
// First, delete old captchas
$expiration = time() - 7200; // Two hour limit
$this->db->where(’captcha_time < ’, $expiration)
->delete(’captcha’);
// Then see if a captcha exists:
$sql = ’SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?’
$binds = array($_POST[’captcha’], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
echo ’You must submit the word that appears in the image.’;
}
9.1.3 Cookie Helper
The Cookie Helper file contains functions that assist in working with cookies.
Page Contents
• Cookie Helper
– Loading this Helper
– set_cookie()
– get_cookie()
– delete_cookie()
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’cookie’);
The following functions are available:
set_cookie()
set_cookie($name = ‘’, $value = ‘’, $expire = ‘’, $domain = ‘’, $path = ‘/’, $prefix = ‘’, $secure = FALSE,
$httponly = FALSE)
• $name (string) – Cookie name
• $value (string) – Cookie value
• $expire (int) – Number of seconds until expiration
• $domain (string) – Cookie domain (usually: .yourdomain.com)
• $path (string) – Cookie path
• $prefix (string) – Cookie name prefix
• $secure (bool) – Whether to only send the cookie through HTTPS
204
Chapter 9.
CodeIgniter Documentation, 3.0-dev
• $httponly (bool) – Whether to hide the cookie from JavaScript
void
This helper function gives you view file friendly syntax to set browser cookies. Refer to the Input Library for a
description of its use, as this function is an alias for CI_Input::set_cookie().
get_cookie()
get_cookie($index = ‘’, $xss_clean = FALSE)
• $index (string) – Cookie name
• $xss_clean (bool) – Whether to apply XSS filtering to the returned value
mixed
This helper function gives you view file friendly syntax to get browser cookies. Refer to the Input Library for a
description of itsuse, as this function is an alias for CI_Input::cookie().
delete_cookie()
delete_cookie($name = ‘’, $domain = ‘’, $path = ‘/’, $prefix = ‘’)
• $name (string) – Cookie name
• $domain (string) – Cookie domain (usually: .yourdomain.com)
• $path (string) – Cookie path
• $prefix (string) – Cookie name prefix
void
Lets you delete a cookie. Unless you’ve set a custom path or other values, only the name of the cookie is needed.
delete_cookie(’name’);
This function is otherwise identical to set_cookie(), except that it does not have the value and expiration parameters. You can submit an array of values in the first parameter or you can set discrete parameters.
delete_cookie($name, $domain, $path, $prefix)
9.1.4 Date Helper
The Date Helper file contains functions that help you work with dates.
9.1. Helpers
205
CodeIgniter Documentation, 3.0-dev
Page Contents
• Date Helper
– Loading this Helper
– now()
– mdate()
– standard_date()
* Supported formats
– local_to_gmt()
– gmt_to_local()
– mysql_to_unix()
– unix_to_human()
– human_to_unix()
– nice_date()
– timespan()
– days_in_month()
– date_range()
– timezones()
– timezone_menu()
– Timezone Reference
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’date’);
The following functions are available:
now()
now($timezone = NULL)
• $timezone (string) – Timezone
int
Returns the current time as a UNIX timestamp, referenced either to your server’s local time or any PHP suported
timezone, based on the “time reference” setting in your config file. If you do not intend to set your master time
reference to any other PHP supported timezone (which you’ll typically do if you run a site that lets each user set their
own timezone settings) there is no benefit to using this function over PHP’s time() function.
echo now(’Australia/Victoria’);
If a timezone is not provided, it will return time() based on the time_reference setting.
mdate()
mdate($datestr = ‘’, $time = ‘’)
• $datestr (string) – Date string
206
Chapter 9.
CodeIgniter Documentation, 3.0-dev
• $time (int) – UNIX timestamp
int
This function is identical to PHP’s date() function, except that it lets you use MySQL style date codes, where each
code letter is preceded with a percent sign, e.g. %Y %m %d
The benefit of doing dates this way is that you don’t have to worry about escaping any characters that are not date
codes, as you would normally have to do with the date() function.
Example:
$datestring = ’Year: %Y Month: %m Day: %d - %h:%i %a’;
$time = time();
echo mdate($datestring, $time);
If a timestamp is not included in the second parameter the current time will be used.
standard_date()
standard_date($fmt = ‘DATE_RFC822’, $time = NULL)
• $fmt (string) – Date format
• $time (int) – UNIX timestamp
string
Lets you generate a date string in one of several standardized formats.
Example:
$format = ’DATE_RFC822’;
$time = time();
echo standard_date($format, $time);
: This function is DEPRECATED. Use the native date() combined with DateTime’s format constants instead:
echo date(DATE_RFC822, time());
9.1. Helpers
207
CodeIgniter Documentation, 3.0-dev
Supported formats
Constant
DATE_ATOM
DATE_COOKIE
DATE_ISO8601
DATE_RFC822
DATE_RFC850
DATE_RFC1036
DATE_RFC1123
DATE_RFC2822
DATE_RSS
DATE_W3C
Description
Atom
HTTP Cookies
ISO-8601
RFC 822
RFC 850
RFC 1036
RFC 1123
RFC 2822
RSS
W3C
Example
2005-08-15T16:13:03+0000
Sun, 14 Aug 2005 16:13:03 UTC
2005-08-14T16:13:03+00:00
Sun, 14 Aug 05 16:13:03 UTC
Sunday, 14-Aug-05 16:13:03 UTC
Sunday, 14-Aug-05 16:13:03 UTC
Sun, 14 Aug 2005 16:13:03 UTC
Sun, 14 Aug 2005 16:13:03 +0000
Sun, 14 Aug 2005 16:13:03 UTC
2005-08-14T16:13:03+0000
local_to_gmt()
local_to_gmt($time = ‘’)
• $time (int) – UNIX timestamp
string
Takes a UNIX timestamp as input and returns it as GMT.
Example:
$gmt = local_to_gmt(time());
gmt_to_local()
gmt_to_local($time = ‘’, $timezone = ‘UTC’, $dst = FALSE)
• $time (int) – UNIX timestamp
• $timezone (string) – Timezone
• $dst (bool) – Whether DST is active
int
Takes a UNIX timestamp (referenced to GMT) as input, and converts it to a localized timestamp based on the timezone
and Daylight Saving Time submitted.
Example:
$timestamp = 1140153693;
$timezone = ’UM8’;
$daylight_saving = TRUE;
echo gmt_to_local($timestamp, $timezone, $daylight_saving);
: For a list of timezones see the reference at the bottom of this page.
208
Chapter 9.
CodeIgniter Documentation, 3.0-dev
mysql_to_unix()
mysql_to_unix($time = ‘’)
• $time (int) – UNIX timestamp
int
Takes a MySQL Timestamp as input and returns it as a UNIX timestamp.
Example:
$unix = mysql_to_unix(’20061124092345’);
unix_to_human()
unix_to_human($time = ‘’, $seconds = FALSE, $fmt = ‘us’)
• $time (int) – UNIX timestamp
• $seconds (bool) – Whether to show seconds
• $fmt (string) – format (us or euro)
integer
Takes a UNIX timestamp as input and returns it in a human readable format with this prototype:
YYYY-MM-DD HH:MM:SS AM/PM
This can be useful if you need to display a date in a form field for submission.
The time can be formatted with or without seconds, and it can be set to European or US format. If only the timestamp
is submitted it will return the time without seconds formatted for the U.S.
Examples:
$now
echo
echo
echo
= time();
unix_to_human($now); // U.S. time, no seconds
unix_to_human($now, TRUE, ’us’); // U.S. time with seconds
unix_to_human($now, TRUE, ’eu’); // Euro time with seconds
human_to_unix()
human_to_unix($datestr = ‘’)
• $datestr (int) – Date string
int UNIX timestamp or FALSE on failure
The opposite of the unix_to_time() function. Takes a “human” time as input and returns it as a UNIX timestamp.
This is useful if you accept “human” formatted dates submitted via a form. Returns boolean FALSE date string passed
to it is not formatted as indicated above.
Example:
9.1. Helpers
209
CodeIgniter Documentation, 3.0-dev
$now = time();
$human = unix_to_human($now);
$unix = human_to_unix($human);
nice_date()
nice_date($bad_date = ‘’, $format = FALSE)
• $bad_date (int) – The terribly formatted date-like string
• $format (string) – Date format to return (same as PHP’s date() function)
string
This function can take a number poorly-formed date formats and convert them into something useful. It also accepts
well-formed dates.
The function will return a UNIX timestamp by default. You can, optionally, pass a format string (the same type as the
PHP date() function accepts) as the second parameter.
Example:
$bad_date = ’199605’;
// Should Produce: 1996-05-01
$better_date = nice_date($bad_date, ’Y-m-d’);
$bad_date = ’9-11-2001’;
// Should Produce: 2001-09-11
$better_date = nice_date($bad_date, ’Y-m-d’);
timespan()
timespan($seconds = 1, $time = ‘’, $units = ‘’)
• $seconds (int) – Number of seconds
• $time (string) – UNIX timestamp
• $units (int) – Number of time units to display
string
Formats a UNIX timestamp so that is appears similar to this:
1 Year, 10 Months, 2 Weeks, 5 Days, 10 Hours, 16 Minutes
The first parameter must contain a UNIX timestamp. The second parameter must contain a timestamp that is greater
that the first timestamp. The thirdparameter is optional and limits the number of time units to display.
If the second parameter empty, the current time will be used.
The most common purpose for this function is to show how much time has elapsed from some point in time in the past
to now.
Example:
210
Chapter 9.
CodeIgniter Documentation, 3.0-dev
$post_date = ’1079621429’;
$now = time();
$units = 2;
echo timespan($post_date, $now, $units);
: The text generated by this function is found in the following language file: language/<your_lang>/date_lang.php
days_in_month()
days_in_month($month = 0, $year = ‘’)
• $month (int) – a numeric month
• $year (int) – a numeric year
int
Returns the number of days in a given month/year. Takes leap years into account.
Example:
echo days_in_month(06, 2005);
If the second parameter is empty, the current year will be used.
date_range()
date_range($unix_start = ‘’, $mixed = ‘’, $is_unix = TRUE, $format = ‘Y-m-d’)
• $unix_start (int) – UNIX timestamp of the range start date
• $mixed (int) – UNIX timestamp of the range end date or interval in days
• $is_unix (bool) – set to FALSE if $mixed is not a timestamp
• $format (string) – Output date format, same as in date()
array
Returns a list of dates within a specified period.
Example:
$range = date_range(’2012-01-01’, ’2012-01-15’);
echo "First 15 days of 2012:";
foreach ($range as $date)
{
echo $date."\n";
}
timezones()
timezones($tz = ‘’)
9.1. Helpers
211
CodeIgniter Documentation, 3.0-dev
• $tz (string) – a numeric timezone
string
Takes a timezone reference (for a list of valid timezones, see the “Timezone Reference” below) and returns the number
of hours offset from UTC.
Example:
echo timezones(’UM5’);
This function is useful when used with timezone_menu().
timezone_menu()
timezone_menu($default = ‘UTC’, $class = ‘’, $name = ‘timezones’, $attributes = ‘’)
• $default (string) – Timezone
• $class (string) – Class name
• $name (string) – Menu name
• $attributes (mixed) – HTML attributes
string
Generates a pull-down menu of timezones, like this one:
This menu is useful if you run a membership site in which your users are allowed to set their local timezone value.
The first parameter lets you set the “selected” state of the menu. For example, to set Pacific time as the default you
will do this:
echo timezone_menu(’UM8’);
Please see the timezone reference below to see the values of this menu.
The second parameter lets you set a CSS class name for the menu.
The fourth parameter lets you set one or more attributes on the generated select tag.
: The text contained in the menu is found in the following language file: language/<your_lang>/date_lang.php
Timezone Reference
The following table indicates each timezone and its location.
Note some of the location lists have been abridged for clarity and formatting.
UM12
UM11
UM10
UM95
UM9
UM8
UM7
212
Time Zone
Location
(UTC - 12:00) Baker/Howland Island
(UTC - 11:00) Samoa Time Zone, Niue
(UTC - 10:00) Hawaii-Aleutian Standard Time, Cook Islands
(UTC - 09:30) Marquesas Islands
(UTC - 09:00) Alaska Standard Time, Gambier Islands
(UTC - 08:00) Pacific Standard Time, Clipperton Island
(UTC - 11:00) Mountain Standard Time
Continued on next page
Chapter 9.
CodeIgniter Documentation, 3.0-dev
UM6
UM5
UM45
UM4
UM35
UM3
UM2
UM1
UTC
UP1
UP2
UP3
UP35
UP4
UP45
UP5
UP55
UP575
UP6
UP65
UP7
UP8
UP875
UP9
UP95
UP10
UP105
UP11
UP115
UP12
UP1275
UP13
UP14
Table 9.1 – continued from previous page
Time Zone
Location
(UTC - 06:00) Central Standard Time
(UTC - 05:00) Eastern Standard Time, Western Caribbean
(UTC - 04:30) Venezuelan Standard Time
(UTC - 04:00) Atlantic Standard Time, Eastern Caribbean
(UTC - 03:30) Newfoundland Standard Time
(UTC - 03:00) Argentina, Brazil, French Guiana, Uruguay
(UTC - 02:00) South Georgia/South Sandwich Islands
(UTC -1:00) Azores, Cape Verde Islands
(UTC) Greenwich Mean Time, Western European Time
(UTC +1:00) Central European Time, West Africa Time
(UTC +2:00) Central Africa Time, Eastern European Time
(UTC +3:00) Moscow Time, East Africa Time
(UTC +3:30) Iran Standard Time
(UTC +4:00) Azerbaijan Standard Time, Samara Time
(UTC +4:30) Afghanistan
(UTC +5:00) Pakistan Standard Time, Yekaterinburg Time
(UTC +5:30) Indian Standard Time, Sri Lanka Time
(UTC +5:45) Nepal Time
(UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time
(UTC +6:30) Cocos Islands, Myanmar
(UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam
(UTC +8:00) Australian Western Standard Time, Beijing Time
(UTC +8:45) Australian Central Western Standard Time
(UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk
(UTC +9:30) Australian Central Standard Time
(UTC +10:00) Australian Eastern Standard Time, Vladivostok Time
(UTC +10:30) Lord Howe Island
(UTC +11:00) Magadan Time, Solomon Islands, Vanuatu
(UTC +11:30) Norfolk Island
(UTC +12:00) Fiji, Gilbert Islands, Kamchatka, New Zealand
(UTC +12:45) Chatham Islands Standard Time
(UTC +13:00) Phoenix Islands Time, Tonga
(UTC +14:00) Line Islands
9.1.5 Directory Helper
The Directory Helper file contains functions that assist in working with directories.
Page Contents
• Directory Helper
– Loading this Helper
– directory_map()
Loading this Helper
This helper is loaded using the following code
9.1. Helpers
213
CodeIgniter Documentation, 3.0-dev
$this->load->helper(’directory’);
The following functions are available:
directory_map()
This function reads the directory path specified in the first parameter and builds an array representation of it and all its
contained files.
directory_map($source_dir[, $directory_depth = 0[, $hidden = FALSE ]])
• $source_dir (string) – path to the ource directory
• $directory_depth (integer) – depth of directories to traverse (0 = fully recursive, 1 = current
dir, etc)
• $hidden (boolean) – whether to include hidden directories
Examples:
$map = directory_map(’./mydirectory/’);
: Paths are almost always relative to your main index.php file.
Sub-folders contained within the directory will be mapped as well. If you wish to control the recursion depth, you can
do so using the second parameter (integer). A depth of 1 will only map the top level directory:
$map = directory_map(’./mydirectory/’, 1);
By default, hidden files will not be included in the returned array. To override this behavior, you may set a third
parameter to true (boolean):
$map = directory_map(’./mydirectory/’, FALSE, TRUE);
Each folder name will be an array index, while its contained files will be numerically indexed. Here is an example of
a typical array:
Array (
[libraries] => Array
(
[0] => benchmark.html
[1] => config.html
["database/"] => Array
(
[0] => query_builder.html
[1] => binds.html
[2] => configuration.html
[3] => connecting.html
[4] => examples.html
[5] => fields.html
[6] => index.html
[7] => queries.html
)
[2] => email.html
[3] => file_uploading.html
[4] => image_lib.html
[5] => input.html
214
Chapter 9.
CodeIgniter Documentation, 3.0-dev
[6]
[7]
[8]
[9]
=>
=>
=>
=>
language.html
loader.html
pagination.html
uri.html
)
9.1.6 Download Helper
The Download Helper lets you download data to your desktop.
Page Contents
• Download Helper
– Loading this Helper
– force_download()
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’download’);
The following functions are available:
force_download()
force_download($filename = ‘’, $data = ‘’, $set_mime = FALSE)
• $filename (string) – Filename
• $data (mixed) – File contents
• $set_mime (bool) – Whether to try to send the actual MIME type
void
Generates server headers which force data to be downloaded to your desktop. Useful with file downloads. The first
parameter is the name you want the downloaded file to be named, the second parameter is the file data.
If you set the second parameter to NULL and $filename is an existing, readable file path, then its content will be
read instead.
If you set the third parameter to boolean TRUE, then the actual file MIME type (based on the filename extension) will
be sent, so that if your browser has a handler for that type - it can use it.
Example:
$data = ’Here is some text!’;
$name = ’mytext.txt’;
force_download($name, $data);
If you want to download an existing file from your server you’ll need to do the following:
9.1. Helpers
215
CodeIgniter Documentation, 3.0-dev
// Contents of photo.jpg will be automatically read
force_download(’/path/to/photo.jpg’, NULL);
9.1.7 Email Helper
The Email Helper provides some assistive functions for working with Email. For a more robust email solution, see
CodeIgniter’s Email Class.
Page Contents
• Email Helper
– Loading this Helper
– valid_email()
– send_email()
: The Email helper is DEPRECATED.
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’email’);
The following functions are available:
valid_email()
valid_email($email)
• $email (string) – Email address
bool
Checks if the input is a correctly formatted e-mail address. Note that is doesn’t actually prove that the address will be
able recieve mail, but simply that it is a validly formed address.
Example:
if (valid_email(’email@somesite.com’))
{
echo ’email is valid’;
}
else
{
echo ’email is not valid’;
}
:
All that this function does is to use PHP’s native filter_var(): | | (bool) filter_var($email, FILTER_VALIDATE_EMAIL);
216
Chapter 9.
CodeIgniter Documentation, 3.0-dev
send_email()
send_email($recipient, $subject, $message)
• $recipient (string) – E-mail address
• $subject (string) – Mail subject
• $message (string) – Message body
bool
Sends an email using PHP’s native mail() function.
: All that this function does is to use PHP’s native mail: | | mail($recipient, $subject, $message);
For a more robust email solution, see CodeIgniter’s Email Library.
9.1.8 File Helper
The File Helper file contains functions that assist in working with files.
Page Contents
• File Helper
– Loading this Helper
– read_file()
– write_file()
– delete_files()
– get_filenames()
– get_dir_file_info()
– get_file_info()
– get_mime_by_extension()
– symbolic_permissions()
– octal_permissions()
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’file’);
The following functions are available:
read_file()
read_file($file)
• $file (string) – File path
string or FALSE on failure
9.1. Helpers
217
CodeIgniter Documentation, 3.0-dev
Returns the data contained in the file specified in the path.
Example:
$string = read_file(’./path/to/file.php’);
The path can be a relative or full server path. Returns FALSE (boolean) on failure.
: The path is relative to your main site index.php file, NOT your controller or view files. CodeIgniter uses a front
controller so paths are always relative to the main site index.
: This function is DEPRECATED. Use the native file_get_contents() instead.
: If your server is running an open_basedir restriction this function might not work if you are trying to access a file
above the calling script.
write_file()
write_file($path, $data, $mode = ‘wb’)
• $path (string) – File path
• $data (string) – Data to write to file
• $mode (string) – fopen() mode
bool
Writes data to the file specified in the path. If the file does not exist then the function will create it.
Example:
$data = ’Some file data’;
if ( ! write_file(’./path/to/file.php’, $data))
{
echo ’Unable to write the file’;
}
else
{
echo ’File written!’;
}
You can optionally set the write mode via the third parameter:
write_file(’./path/to/file.php’, $data, ’r+’);
The default mode is ‘wb’. Please see the PHP user guide for mode options.
: The path is relative to your main site index.php file, NOT your controller or view files. CodeIgniter uses a front
controller so paths are always relative to the main site index.
: This function acquires an exclusive lock on the file while writing to it.
218
Chapter 9.
CodeIgniter Documentation, 3.0-dev
delete_files()
delete_files($path, $del_dir = FALSE, $htdocs = FALSE)
• $path (string) – Directory path
• $del_dir (bool) – Whether to also delete directories
• $htdocs (bool) – Whether to skip deleting .htaccess and index page files
bool
Deletes ALL files contained in the supplied path.
Example:
delete_files(’./path/to/directory/’);
If the second parameter is set to TRUE, any directories contained within the supplied root path will be deleted as well.
Example:
delete_files(’./path/to/directory/’, TRUE);
: The files must be writable or owned by the system in order to be deleted.
get_filenames()
get_filenames($source_dir, $include_path = FALSE)
• $source_dir (string) – Directory path
• $include_path (bool) – Whether to include the path as part of the filenames
array
Takes a server path as input and returns an array containing the names of all files contained within it. The file path can
optionally be added to the file names by setting the second parameter to TRUE.
Example:
$controllers = get_filenames(APPPATH.’controllers/’);
get_dir_file_info()
get_dir_file_info($source_dir, $top_level_only)
• $source_dir (string) – Directory path
• $top_level_only (bool) – Whether to look only at the specified directory (excluding subdirectories)
array
9.1. Helpers
219
CodeIgniter Documentation, 3.0-dev
Reads the specified directory and builds an array containing the filenames, filesize, dates, and permissions. Sub-folders
contained within the specified path are only read if forced by sending the second parameter to FALSE, as this can be
an intensive operation.
Example:
$models_info = get_dir_file_info(APPPATH.’models/’);
get_file_info()
Given a file and path, returns (optionally) the name, path, size and date modified information attributes for a file.
Second parameter allows you to explicitly declare what information you want returned.
Valid $returned_values options are: name, size, date, readable, writeable, executable and fileperms.
: The writable attribute is checked via PHP’s is_writeable() function, which known to have issues on the IIS
webserver. Consider using fileperms instead, which returns information from PHP’s fileperms() function.
get_mime_by_extension()
get_mime_by_extension($filename)
• $filename (string) – File name
string or FALSE on failure
Translates a filename extension into a MIME type based on config/mimes.php. Returns FALSE if it can’t determine
the type, or read the MIME config file.
$file = ’somefile.png’;
echo $file.’ is has a mime type of ’.get_mime_by_extension($file);
: This is not an accurate way of determining file MIME types, and is here strictly for convenience. It should not be
used for security purposes.
symbolic_permissions()
symbolic_permissions($perms)
• $perms (int) – Permissions
string
Takes numeric permissions (such as is returned by fileperms()) and returns standard symbolic notation of file
permissions.
echo symbolic_permissions(fileperms(’./index.php’));
220
// -rw-r--r--
Chapter 9.
CodeIgniter Documentation, 3.0-dev
octal_permissions()
octal_permissions($perms)
• $perms (int) – Permissions
string
Takes numeric permissions (such as is returned by fileperms()) and returns a three character octal notation of file
permissions.
echo octal_permissions(fileperms(’./index.php’)); // 644
9.1.9 Form Helper
The Form Helper file contains functions that assist in working with forms.
Page Contents
• Form Helper
– Loading this Helper
– form_open()
* Adding Attributes
* Adding Hidden Input Fields
– form_open_multipart()
– form_hidden()
– form_input()
– form_password()
– form_upload()
– form_textarea()
– form_dropdown()
– form_multiselect()
– form_fieldset()
– form_fieldset_close()
– form_checkbox()
– form_radio()
– form_label()
– form_submit()
– form_reset()
– form_button()
– form_close()
– form_prep()
– set_value()
– set_select()
– set_checkbox()
– set_radio()
– form_error()
– validation_errors()
Loading this Helper
This helper is loaded using the following code:
9.1. Helpers
221
CodeIgniter Documentation, 3.0-dev
$this->load->helper(’form’);
The following functions are available:
form_open()
form_open($action = ‘’, $attributes = ‘’, $hidden = array())
• $action (string) – Form action/target URI string
• $attributes (array) – HTML attributes
• $hidden (array) – An array of hidden fields’ definitions
string
Creates an opening form tag with a base URL built from your config preferences. It will optionally let you add form
attributes and hidden input fields, and will always add the accept-charset attribute based on the charset value in your
config file.
The main benefit of using this tag rather than hard coding your own HTML is that it permits your site to be more
portable in the event your URLs ever change.
Here’s a simple example:
echo form_open(’email/send’);
The above example would create a form that points to your base URL plus the “email/send” URI segments, like this:
<form method="post" accept-charset="utf-8" action="http://example.com/index.php/email/send">
Adding Attributes
Attributes can be added by passing an associative array to the second parameter, like this:
$attributes = array(’class’ => ’email’, ’id’ => ’myform’);
echo form_open(’email/send’, $attributes);
Alternatively, you can specify the second parameter as a string:
echo form_open(’email/send’, ’class="email" id="myform"’);
The above examples would create a form similar to this:
<form method="post" accept-charset="utf-8" action="http://example.com/index.php/email/send" class="em
Adding Hidden Input Fields
Hidden fields can be added by passing an associative array to the third parameter, like this:
$hidden = array(’username’ => ’Joe’, ’member_id’ => ’234’);
echo form_open(’email/send’, ’’, $hidden);
You can skip the second parameter by passing any falsy value to it.
The above example would create a form similar to this:
222
Chapter 9.
CodeIgniter Documentation, 3.0-dev
<form method="post" accept-charset="utf-8" action="http://example.com/index.php/email/send">
<input type="hidden" name="username" value="Joe" />
<input type="hidden" name="member_id" value="234" />
form_open_multipart()
form_open_multipart($action = ‘’, $attributes = array(), $hidden = array())
• $action (string) – Form action/target URI string
• $attributes (array) – HTML attributes
• $hidden (array) – An array of hidden fields’ definitions
string
This function is absolutely identical to form_open() above, except that it adds a multipart attribute, which is
necessary if you would like to use the form to upload files with.
form_hidden()
form_hidden($name, $value = ‘’)
• $name (string) – Field name
• $value (string) – Field value
string
Lets you generate hidden input fields. You can either submit a name/value string to create one field:
form_hidden(’username’, ’johndoe’);
// Would produce: <input type="hidden" name="username" value="johndoe" />
... or you can submit an associative array to create multiple fields:
$data = array(
’name’ => ’John Doe’,
’email’ => ’john@example.com’,
’url’
=> ’http://example.com’
);
echo form_hidden($data);
/*
Would produce:
<input type="hidden" name="name" value="John Doe" />
<input type="hidden" name="email" value="john@example.com" />
<input type="hidden" name="url" value="http://example.com" />
*/
You can also pass an associative array to the value field:
$data = array(
’name’ => ’John Doe’,
’email’ => ’john@example.com’,
9.1. Helpers
223
CodeIgniter Documentation, 3.0-dev
’url’
=> ’http://example.com’
);
echo form_hidden(’my_array’, $data);
/*
Would produce:
<input type="hidden" name="my_array[name]" value="John Doe" />
<input type="hidden" name="my_array[email]" value="john@example.com" />
<input type="hidden" name="my_array[url]" value="http://example.com" />
*/
If you want to create hidden input fields with extra attributes:
$data = array(
’type’
’name’
’id’
’value’
’class’
);
=>
=>
=>
=>
=>
’hidden’,
’email’,
’hiddenemail’,
’john@example.com’,
’hiddenemail’
echo form_input($data);
/*
Would produce:
<input type="hidden" name="email" value="john@example.com" id="hiddenemail" class="hiddenemai
*/
form_input()
form_input($data = ‘’, $value = ‘’, $extra = ‘’)
• $data (array) – Field attributes data
• $value (string) – Field value
• $extra (string) – Extra attributes to be added to the tag as is
string
Lets you generate a standard text input field. You can minimally pass the field name and value in the first and second
parameter:
echo form_input(’username’, ’johndoe’);
Or you can pass an associative array containing any data you wish your form to contain:
$data = array(
’name’
’id’
’value’
’maxlength’
’size’
’style’
);
224
=>
=>
=>
=>
=>
=>
’username’,
’username’,
’johndoe’,
’100’,
’50’,
’width:50%’
Chapter 9.
CodeIgniter Documentation, 3.0-dev
echo form_input($data);
/*
Would produce:
<input type="text" name="username" value="johndoe" id="username" maxlength="100" size="50" st
*/
If you would like your form to contain some additional data, like JavaScript, you can pass it as a string in the third
parameter:
$js = ’onClick="some_function()"’;
echo form_input(’username’, ’johndoe’, $js);
form_password()
form_password($data = ‘’, $value = ‘’, $extra = ‘’)
• $data (array) – Field attributes data
• $value (string) – Field value
• $extra (string) – Extra attributes to be added to the tag as is
string
This function is identical in all respects to the form_input() function above except that it uses the “password”
input type.
form_upload()
form_upload($data = ‘’, $value = ‘’, $extra = ‘’)
• $data (array) – Field attributes data
• $value (string) – Field value
• $extra (string) – Extra attributes to be added to the tag as is
string
This function is identical in all respects to the form_input() function above except that it uses the “file” input
type, allowing it to be used to upload files.
form_textarea()
form_textarea($data = ‘’, $value = ‘’, $extra = ‘’)
• $data (array) – Field attributes data
• $value (string) – Field value
• $extra (string) – Extra attributes to be added to the tag as is
9.1. Helpers
225
CodeIgniter Documentation, 3.0-dev
string
This function is identical in all respects to the form_input() function above except that it generates a “textarea”
type.
form_dropdown()
form_dropdown($name = ‘’, $options = array(), $selected = array(), $extra = ‘’)
• $name (string) – Field name
• $options (array) – An associative array of options to be listed
• $selected (array) – List of fields to mark with the selected attribute
• $extra (string) – Extra attributes to be added to the tag as is
string
Lets you create a standard drop-down field. The first parameter will contain the name of the field, the second parameter
will contain an associative array of options, and the third parameter will contain the value you wish to be selected.
You can also pass an array of multiple items through the third parameter, and CodeIgniter will create a multiple select
for you.
Example:
$options = array(
’small’
’med’
’large’
’xlarge’
);
=>
=>
=>
=>
’Small Shirt’,
’Medium Shirt’,
’Large Shirt’,
’Extra Large Shirt’,
$shirts_on_sale = array(’small’, ’large’);
echo form_dropdown(’shirts’, $options, ’large’);
/*
Would produce:
<select name="shirts">
<option value="small">Small Shirt</option>
<option value="med">Medium Shirt</option>
<option value="large" selected="selected">Large Shirt</option>
<option value="xlarge">Extra Large Shirt</option>
</select>
*/
echo form_dropdown(’shirts’, $options, $shirts_on_sale);
/*
Would produce:
<select name="shirts" multiple="multiple">
<option value="small" selected="selected">Small Shirt</option>
<option value="med">Medium Shirt</option>
<option value="large" selected="selected">Large Shirt</option>
<option value="xlarge">Extra Large Shirt</option>
</select>
*/
226
Chapter 9.
CodeIgniter Documentation, 3.0-dev
If you would like the opening <select> to contain additional data, like an id attribute or JavaScript, you can pass it as
a string in the fourth parameter:
$js = ’id="shirts" onChange="some_function();"’;
echo form_dropdown(’shirts’, $options, ’large’, $js);
If the array passed as $options is a multidimensional array, then form_dropdown() will produce an <optgroup>
with the array key as the label.
form_multiselect()
form_multiselect($name = ‘’, $options = array(), $selected = array(), $extra = ‘’)
• $name (string) – Field name
• $options (array) – An associative array of options to be listed
• $selected (array) – List of fields to mark with the selected attribute
• $extra (string) – Extra attributes to be added to the tag as is
string
Lets you create a standard multiselect field. The first parameter will contain the name of the field, the second parameter
will contain an associative array of options, and the third parameter will contain the value or values you wish to be
selected.
The parameter usage is identical to using form_dropdown() above, except of course that the name of the field will
need to use POST array syntax, e.g. foo[].
form_fieldset()
form_fieldset($legend_text = ‘’, $attributes = array())
• $legend_text (string) – Text to put in the <legend> tag
• $attributes (array) – Attributes to be set on the <fieldset> tag
string
Lets you generate fieldset/legend fields.
Example:
echo form_fieldset(’Address Information’);
echo "<p>fieldset content here</p>\n";
echo form_fieldset_close();
/*
Produces:
<fieldset>
<legend>Address Information</legend>
<p>form content here</p>
</fieldset>
*/
9.1. Helpers
227
CodeIgniter Documentation, 3.0-dev
Similar to other functions, you can submit an associative array in the second parameter if you prefer to set additional
attributes:
$attributes = array(
’id’
=> ’address_info’,
’class’ => ’address_info’
);
echo form_fieldset(’Address Information’, $attributes);
echo "<p>fieldset content here</p>\n";
echo form_fieldset_close();
/*
Produces:
<fieldset id="address_info" class="address_info">
<legend>Address Information</legend>
<p>form content here</p>
</fieldset>
*/
form_fieldset_close()
form_fieldset_close($extra = ‘’)
• $extra (string) – Anything to append after the closing tag, as is
string
Produces a closing </fieldset> tag. The only advantage to using this function is it permits you to pass data to it which
will be added below the tag. For example
$string = ’</div></div>’;
echo form_fieldset_close($string);
// Would produce: </fieldset></div></div>
form_checkbox()
form_checkbox($data = ‘’, $value = ‘’, $checked = FALSE, $extra = ‘’)
• $data (array) – Field attributes data
• $value (string) – Field value
• $checked (bool) – Whether to mark the checkbox as being checked
• $extra (string) – Extra attributes to be added to the tag as is
string
Lets you generate a checkbox field. Simple example:
echo form_checkbox(’newsletter’, ’accept’, TRUE);
// Would produce: <input type="checkbox" name="newsletter" value="accept" checked="checked" />
228
Chapter 9.
CodeIgniter Documentation, 3.0-dev
The third parameter contains a boolean TRUE/FALSE to determine whether the box should be checked or not.
Similar to the other form functions in this helper, you can also pass an array of attributes to the function:
$data = array(
’name’
’id’
’value’
’checked’
’style’
);
=>
=>
=>
=>
=>
’newsletter’,
’newsletter’,
’accept’,
TRUE,
’margin:10px’
echo form_checkbox($data);
// Would produce: <input type="checkbox" name="newsletter" id="newsletter" value="accept" checked="ch
Also as with other functions, if you would like the tag to contain additional data like JavaScript, you can pass it as a
string in the fourth parameter:
$js = ’onClick="some_function()"’;
echo form_checkbox(’newsletter’, ’accept’, TRUE, $js)
form_radio()
form_radio($data = ‘’, $value = ‘’, $checked = FALSE, $extra = ‘’)
• $data (array) – Field attributes data
• $value (string) – Field value
• $checked (bool) – Whether to mark the radio button as being checked
• $extra (string) – Extra attributes to be added to the tag as is
string
This function is identical in all respects to the form_checkbox() function above except that it uses the “radio”
input type.
form_label()
form_label($label_text = ‘’, $id = ‘’, $attributes = array())
• $label_text (string) – Text to put in the <label> tag
• $id (string) – ID of the form element that we’re making a label for
• $attributes (string) – HTML attributes
string
Lets you generate a <label>. Simple example:
echo form_label(’What is your Name’, ’username’);
// Would produce: <label for="username">What is your Name</label>
Similar to other functions, you can submit an associative array in the third parameter if you prefer to set additional
attributes.
9.1. Helpers
229
CodeIgniter Documentation, 3.0-dev
Example:
$attributes = array(
’class’ => ’mycustomclass’,
’style’ => ’color: #000;’
);
echo form_label(’What is your Name’, ’username’, $attributes);
// Would produce: <label for="username" class="mycustomclass" style="color: #000;">What is your Name
form_submit()
form_submit($data = ‘’, $value = ‘’, $extra = ‘’)
• $data (string) – Button name
• $value (string) – Button value
• $extra (string) – Extra attributes to be added to the tag as is
string
Lets you generate a standard submit button. Simple example:
echo form_submit(’mysubmit’, ’Submit Post!’);
// Would produce: <input type="submit" name="mysubmit" value="Submit Post!" />
Similar to other functions, you can submit an associative array in the first parameter if you prefer to set your own
attributes. The third parameter lets you add extra data to your form, like JavaScript.
form_reset()
form_reset($data = ‘’, $value = ‘’, $extra = ‘’)
• $data (string) – Button name
• $value (string) – Button value
• $extra (string) – Extra attributes to be added to the tag as is
string
Lets you generate a standard reset button. Use is identical to form_submit().
form_button()
form_button($data = ‘’, $content = ‘’, $extra = ‘’)
• $data (string) – Button name
• $content (string) – Button label
• $extra (string) – Extra attributes to be added to the tag as is
string
230
Chapter 9.
CodeIgniter Documentation, 3.0-dev
Lets you generate a standard button element. You can minimally pass the button name and content in the first and
second parameter:
echo form_button(’name’,’content’);
// Would produce: <button name="name" type="button">Content</button>
Or you can pass an associative array containing any data you wish your form to contain:
$data = array(
’name’
’id’
’value’
’type’
’content’
);
=>
=>
=>
=>
=>
’button’,
’button’,
’true’,
’reset’,
’Reset’
echo form_button($data);
// Would produce: <button name="button" id="button" value="true" type="reset">Reset</button>
If you would like your form to contain some additional data, like JavaScript, you can pass it as a string in the third
parameter:
$js = ’onClick="some_function()"’;
echo form_button(’mybutton’, ’Click Me’, $js);
form_close()
form_close($extra = ‘’)
• $extra (string) – Anything to append after the closing tag, as is
string
Produces a closing </form> tag. The only advantage to using this function is it permits you to pass data to it which
will be added below the tag. For example:
$string = ’</div></div>’;
echo form_close($string);
// Would produce: </form> </div></div>
form_prep()
form_prep($str = ‘’, $is_textarea = FALSE)
• $str (string) – Value to escape
• $is_textarea (bool) – Whether we’re preparing for <textarea> or a regular input tag
string
Allows you to safely use HTML and characters such as quotes within form elements without breaking out of the form.
Consider this example:
$string = ’Here is a string containing "quoted" text.’;
<input type="text" name="myform" value="$string" />
9.1. Helpers
231
CodeIgniter Documentation, 3.0-dev
Since the above string contains a set of quotes it will cause the form to break. The form_prep() function converts
HTML so that it can be used safely:
<input type="text" name="myform" value="<?php echo form_prep($string); ?>" />
: If you use any of the form helper functions listed in this page the form values will be prepped automatically, so there
is no need to call this function. Use it only if you are creating your own form elements.
set_value()
set_value($field = ‘’, $default = ‘’, $is_textarea = FALSE)
• $field (string) – Field name
• $default (string) – Default value
• $is_textarea (bool) – Whether we’re setting <textarea> content
string
Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the
function. The second (optional) parameter allows you to set a default value for the form.
Example:
<input type="text" name="quantity" value="<?=set_value(’quantity’, ’0’);?>" size="50" />
The above form will show “0” when loaded for the first time.
set_select()
set_select($field = ‘’, $value = ‘’, $default = FALSE)
• $field (string) – Field name
• $value (string) – Value to check for
• $default (string) – Whether the value is also a default one
string
If you use a <select> menu, this function permits you to display the menu item that was selected.
The first parameter must contain the name of the select menu, the second parameter must contain the value of each
item, and the third (optional) parameter lets you set an item as the default (use boolean TRUE/FALSE).
Example:
<select name="myselect">
<option value="one" <?php echo set_select(’myselect’, ’one’, TRUE); ?> >One</option>
<option value="two" <?php echo set_select(’myselect’, ’two’); ?> >Two</option>
<option value="three" <?php echo set_select(’myselect’, ’three’); ?> >Three</option>
</select>
232
Chapter 9.
CodeIgniter Documentation, 3.0-dev
set_checkbox()
set_checkbox($field = ‘’, $value = ‘’, $default = FALSE)
• $field (string) – Field name
• $value (string) – Value to check for
• $default (string) – Whether the value is also a default one
string
Permits you to display a checkbox in the state it was submitted.
The first parameter must contain the name of the checkbox, the second parameter must contain its value, and the third
(optional) parameter lets you set an item as the default (use boolean TRUE/FALSE).
Example:
<input type="checkbox" name="mycheck" value="1" <?php echo set_checkbox(’mycheck’, ’1’); ?> />
<input type="checkbox" name="mycheck" value="2" <?php echo set_checkbox(’mycheck’, ’2’); ?> />
set_radio()
set_radio($field = ‘’, $value = ‘’, $default = FALSE)
• $field (string) – Field name
• $value (string) – Value to check for
• $default (string) – Whether the value is also a default one
string
Permits you to display radio buttons in the state they were submitted.
set_checkbox() function above.
This function is identical to the
Example:
<input type="radio" name="myradio" value="1" <?php echo
<input type="radio" name="myradio" value="2" <?php echo
set_radio(’myradio’, ’1’, TRUE); ?> />
set_radio(’myradio’, ’2’); ?> />
: If you are using the Form Validation class, you must always specify a rule for your field, even if empty, in order for
the set_*() functions to work. This is because if a Form Validation object is defined, the control for set_*() is
handed over to a method of the class instead of the generic helper function.
form_error()
form_error($field = ‘’, $prefix = ‘’, $suffix = ‘’)
• $field (string) – Field name
• $prefix (string) – Error opening tag
• $suffix (string) – Error closing tag
9.1. Helpers
233
CodeIgniter Documentation, 3.0-dev
string
Returns a validation error message from the Form Validation Library, associated with the specified field name. You
can optionally specify opening and closing tag(s) to put around the error message.
Example:
// Assuming that the ’username’ field value was incorrect:
echo form_error(’myfield’, ’<div class="error">’, ’</div>’);
// Would produce: <div class="error">Error message associated with the "username" field.</div>
validation_errors()
validation_errors($prefix = ‘’, $suffix = ‘’)
• $prefix (string) – Error opening tag
• $suffix (string) – Error closing tag
string
Similarly to the form_error() function, returns all validation error messages produced by the Form Validation
Library, with optional opening and closing tags around each of the messages.
Example:
echo validation_errors(’<span class="error">’, ’</span>’);
/*
Would produce, e.g.:
<span class="error">The "email" field doesn’t contain a valid e-mail address!</span>
<span class="error">The "password" field doesn’t match the "repeat_password" field!</span>
*/
9.1.10 HTML Helper
The HTML Helper file contains functions that assist in working with HTML.
Page Contents
• HTML Helper
– Loading this Helper
– br()
– heading()
– img()
– link_tag()
– nbs()
– ul() and ol()
– meta()
– doctype()
234
Chapter 9.
CodeIgniter Documentation, 3.0-dev
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’html’);
The following functions are available:
br()
br($count = 1)
• $count (int) – Number of times to repeat the tag
string
Generates line break tags (<br />) based on the number you submit. Example:
echo br(3);
The above would produce: <br /><br /><br />
heading()
heading($data = ‘’, $h = ‘1’, $attributes = ‘’)
• $data (string) – Content
• $h (string) – Heading level
• $attributes (array) – HTML attributes
string
Lets you create HTML heading tags. The first parameter will contain the data, the second the size of the heading.
Example:
echo heading(’Welcome!’, 3);
The above would produce: <h3>Welcome!</h3>
Additionally, in order to add attributes to the heading tag such as HTML classes, ids or inline styles, a third parameter
is available:
echo heading(’Welcome!’, 3, ’class="pink"’)
The above code produces: <h3 class=”pink”>Welcome!<<h3>
img()
img($src = ‘’, $index_page = FALSE, $attributes = ‘’)
• $src (string) – Image source data
• $index_page (bool) – Whether to treat $src as a routed URI string
9.1. Helpers
235
CodeIgniter Documentation, 3.0-dev
• $attributes (array) – HTML attributes
string
Lets you create HTML <img /> tags. The first parameter contains the image source. Example:
echo img(’images/picture.jpg’); // gives <img src="http://site.com/images/picture.jpg" />
There is an optional second parameter that is a TRUE/FALSE value that specifics if the src should have the page
specified by $config[’index_page’] added to the address it creates. Presumably, this would be if you were
using a media controller:
echo img(’images/picture.jpg’, TRUE); // gives <img src="http://site.com/index.php/images/picture.jpg
Additionally, an associative array can be passed to the img() function for complete control over all attributes and
values. If an alt attribute is not provided, CodeIgniter will generate an empty string.
Example:
$image_properties = array(
’src’
=> ’images/picture.jpg’,
’alt’
=> ’Me, demonstrating how to eat 4 slices of pizza at one time’,
’class’ => ’post_images’,
’width’ => ’200’,
’height’=> ’200’,
’title’ => ’That was quite a night’,
’rel’
=> ’lightbox’
);
img($image_properties);
// <img src="http://site.com/index.php/images/picture.jpg" alt="Me, demonstrating how to eat 4 slices
link_tag()
ling_tag($href = ‘’, $rel = ‘stylesheet’, $type = ‘text/css’, $title = ‘’, $media = ‘’, $index_page = FALSE)
• $href (string) – What are we linking to
• $rel (string) – Relation type
• $type (string) – Type of the related document
• $title (string) – Link title
• $media (string) – Media type
• $index_page (bool) – Whether to treat $src as a routed URI string
string
Lets you create HTML <link /> tags. This is useful for stylesheet links, as well as other links. The parameters are href,
with optional rel, type, title, media and index_page.
index_page is a boolean value that specifies if the
$config[’index_page’] added to the address it creates.
href
should
have
the
page
specified
by
Example:
echo link_tag(’css/mystyles.css’);
// gives <link href="http://site.com/css/mystyles.css" rel="stylesheet" type="text/css" />
236
Chapter 9.
CodeIgniter Documentation, 3.0-dev
Further examples:
echo link_tag(’favicon.ico’, ’shortcut icon’, ’image/ico’);
// <link href="http://site.com/favicon.ico" rel="shortcut icon" type="image/ico" />
echo link_tag(’feed’, ’alternate’, ’application/rss+xml’, ’My RSS Feed’);
// <link href="http://site.com/feed" rel="alternate" type="application/rss+xml" title="My RSS Feed" /
Additionally, an associative array can be passed to the link() function for complete control over all attributes and
values:
$link = array(
’href’
’rel’
’type’
’media’
);
=>
=>
=>
=>
’css/printer.css’,
’stylesheet’,
’text/css’,
’print’
echo link_tag($link);
// <link href="http://site.com/css/printer.css" rel="stylesheet" type="text/css" media="print" />
nbs()
nbs($num = 1)
• $num (int) – Number of space entities to produce
string
Generates non-breaking spaces (&nbsp;) based on the number you submit. Example:
echo nbs(3);
The above would produce:
&nbsp;&nbsp;&nbsp;
ul() and ol()
ul($list, $attributes = ‘’)
• $list (array) – List entries
• $attributes (array) – HTML attributes
string
Permits you to generate ordered or unordered HTML lists from simple or multi-dimensional arrays. Example:
$list = array(
’red’,
’blue’,
’green’,
’yellow’
);
9.1. Helpers
237
CodeIgniter Documentation, 3.0-dev
$attributes = array(
’class’ => ’boldlist’,
’id’
=> ’mylist’
);
echo ul($list, $attributes);
The above code will produce this:
<ul class="boldlist" id="mylist">
<li>red</li>
<li>blue</li>
<li>green</li>
<li>yellow</li>
</ul>
Here is a more complex example, using a multi-dimensional array:
$attributes = array(
’class’ => ’boldlist’,
’id’
=> ’mylist’
);
$list = array(
’colors’ => array(
’red’,
’blue’,
’green’
),
’shapes’ => array(
’round’,
’square’,
’circles’ => array(
’ellipse’,
’oval’,
’sphere’
)
),
’moods’ => array(
’happy’,
’upset’ => array(
’defeated’ => array(
’dejected’,
’disheartened’,
’depressed’
),
’annoyed’,
’cross’,
’angry’
)
)
);
echo ul($list, $attributes);
The above code will produce this:
<ul class="boldlist" id="mylist">
<li>colors
238
Chapter 9.
CodeIgniter Documentation, 3.0-dev
<ul>
<li>red</li>
<li>blue</li>
<li>green</li>
</ul>
</li>
<li>shapes
<ul>
<li>round</li>
<li>suare</li>
<li>circles
<ul>
<li>elipse</li>
<li>oval</li>
<li>sphere</li>
</ul>
</li>
</ul>
</li>
<li>moods
<ul>
<li>happy</li>
<li>upset
<ul>
<li>defeated
<ul>
<li>dejected</li>
<li>disheartened</li>
<li>depressed</li>
</ul>
</li>
<li>annoyed</li>
<li>cross</li>
<li>angry</li>
</ul>
</li>
</ul>
</li>
</ul>
ol($list, $attributes = ‘’)
• $list (array) – List entries
• $attributes (array) – HTML attributes
string
Identical to ul(), only it produces the <ol> tag for ordered lists instead of <ul>.
meta()
meta($name = ‘’, $content = ‘’, $type = ‘name’, $newline = “n”)
• $name (string) – Meta name
9.1. Helpers
239
CodeIgniter Documentation, 3.0-dev
• $content (string) – Meta content
• $type (string) – Meta type
• $newline (string) – Newline character
string
Helps you generate meta tags. You can pass strings to the function, or simple arrays, or multidimensional ones.
Examples:
echo meta(’description’, ’My Great site’);
// Generates: <meta name="description" content="My Great Site" />
echo meta(’Content-type’, ’text/html; charset=utf-8’, ’equiv’);
// Note the third parameter. Can be "equiv" or "name"
// Generates: <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
echo meta(array(’name’ => ’robots’, ’content’ => ’no-cache’));
// Generates: <meta name="robots" content="no-cache" />
$meta = array(
array(
’name’ => ’robots’,
’content’ => ’no-cache’
),
array(
’name’ => ’description’,
’content’ => ’My Great Site’
),
array(
’name’ => ’keywords’,
’content’ => ’love, passion, intrigue, deception’
),
array(
’name’ => ’robots’,
’content’ => ’no-cache’
),
array(
’name’ => ’Content-type’,
’content’ => ’text/html; charset=utf-8’, ’type’ => ’equiv’
)
);
echo meta($meta);
// Generates:
// <meta name="robots" content="no-cache" />
// <meta name="description" content="My Great Site" />
// <meta name="keywords" content="love, passion, intrigue, deception" />
// <meta name="robots" content="no-cache" />
// <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
doctype()
doctype($type = ‘xhtml1-strict’)
• $type (string) – Doctype name
240
Chapter 9.
CodeIgniter Documentation, 3.0-dev
Helps you generate document type declarations, or DTD’s. XHTML 1.0 Strict is used by default, but many doctypes
are available.
Example:
echo doctype(); // <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xht
echo doctype(’html4-trans’); // <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/
The following is a list of doctype choices. These are configurable, and pulled from application/config/doctypes.php
Doctype
XHTML 1.1
Option
Result
doc<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
type(‘xhtml11’) “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd“>
XHTML 1.0 Strict doctype(‘xhtml1-<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
strict’)
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd“>
XHTML 1.0
doctype(‘xhtml1-<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0
Transitional
trans’)
Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>
XHTML 1.0
doctype(‘xhtml1-<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Frameset//EN”
Frameset
frame’)
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd“>
XHTML Basic 1.1 doctype(‘xhtml- <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML Basic 1.1//EN”
basic11’)
“http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd“>
HTML 5
doc<!DOCTYPE html>
type(‘html5’)
HTML 4 Strict
doctype(‘html4- <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
strict’)
“http://www.w3.org/TR/html4/strict.dtd“>
HTML 4
doctype(‘html4- <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01
Transitional
trans’)
Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd“>
HTML 4 Frameset doctype(‘html4- <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Frameset//EN”
frame’)
“http://www.w3.org/TR/html4/frameset.dtd“>
MathML 1.01
doc<!DOCTYPE math SYSTEM
type(‘mathml1’) “http://www.w3.org/Math/DTD/mathml1/mathml.dtd“>
MathML 2.0
doc<!DOCTYPE math PUBLIC “-//W3C//DTD MathML 2.0//EN”
type(‘mathml2’) “http://www.w3.org/Math/DTD/mathml2/mathml2.dtd“>
SVG 1.0
doc<!DOCTYPE svg PUBLIC “-//W3C//DTD SVG 1.0//EN”
type(‘svg10’) “http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd“>
SVG 1.1 Full
doc<!DOCTYPE svg PUBLIC “-//W3C//DTD SVG 1.1//EN”
type(‘svg11’) “http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd“>
SVG 1.1 Basic
doctype(‘svg11- <!DOCTYPE svg PUBLIC “-//W3C//DTD SVG 1.1 Basic//EN”
basic’)
“http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd“>
SVG 1.1 Tiny
doctype(‘svg11- <!DOCTYPE svg PUBLIC “-//W3C//DTD SVG 1.1 Tiny//EN”
tiny’)
“http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd“>
XHTML+MathML+SVG
doctype(‘xhtml- <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1 plus MathML
(XHTML host)
math-svg2.0 plus SVG 1.1//EN”
xh’)
“http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd“>
XHTML+MathML+SVG
doctype(‘xhtml- <!DOCTYPE svg:svg PUBLIC “-//W3C//DTD XHTML 1.1 plus MathML
(SVG host)
math-svg2.0 plus SVG 1.1//EN”
sh’)
“http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd”>
XHTML+RDFa
doctype(‘xhtml- <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML+RDFa 1.0//EN”
1.0
rdfa-1’)
“http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd“>
XHTML+RDFa
doctype(‘xhtml- <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML+RDFa 1.1//EN”
1.1
rdfa-2’)
“http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd“>
9.1. Helpers
241
CodeIgniter Documentation, 3.0-dev
9.1.11 Inflector Helper
The Inflector Helper file contains functions that permits you to change words to plural, singular, camel case, etc.
Page Contents
• Inflector Helper
– Loading this Helper
– singular()
– plural()
– camelize()
– underscore()
– humanize()
– is_countable()
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’inflector’);
The following functions are available:
singular()
singular($str)
• $str (string) – Input string
string
Changes a plural word to singular. Example:
echo singular(’dogs’); // Prints ’dog’
plural()
plural($str)
• $str (string) – Input string
string
Changes a singular word to plural. Example:
echo plural(’dog’); // Prints ’dogs’
242
Chapter 9.
CodeIgniter Documentation, 3.0-dev
camelize()
camelize($str)
• $str (string) – Input string
string
Changes a string of words separated by spaces or underscores to camel case. Example:
echo camelize(’my_dog_spot’); // Prints ’myDogSpot’
underscore()
camelize($str)
• $str (string) – Input string
string
Takes multiple words separated by spaces and underscores them. Example:
echo underscore(’my dog spot’); // Prints ’my_dog_spot’
humanize()
camelize($str)
• $str (string) – Input string
• $separator (string) – Input separator
string
Takes multiple words separated by underscores and adds spaces between them. Each word is capitalized.
Example:
echo humanize(’my_dog_spot’); // Prints ’My Dog Spot’
To use dashes instead of underscores:
echo humanize(’my-dog-spot’, ’-’); // Prints ’My Dog Spot’
is_countable()
is_countable($word)
• $word (string) – Input string
bool
Checks if the given word has a plural version. Example:
9.1. Helpers
243
CodeIgniter Documentation, 3.0-dev
is_countable(’equipment’); // Returns FALSE
9.1.12 Language Helper
The Language Helper file contains functions that assist in working with language files.
Page Contents
• Language Helper
– Loading this Helper
– lang()
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’language’);
The following functions are available:
lang()
lang($line, $for = ‘’, $attributes = array())
• $line (string) – Language line key
• $for (string) – HTML “for” attribute (ID of the element we’re creating a label for)
• $attributes (array) – Any additional HTML attributes
string
This function returns a line of text from a loaded language file with simplified syntax that may be more desirable for
view files than CI_Lang::line().
Example:
echo lang(’language_key’, ’form_item_id’, array(’class’ => ’myClass’);
// Outputs: <label for="form_item_id" class="myClass">Language line</label>
9.1.13 Number Helper
The Number Helper file contains functions that help you work with numeric data.
Page Contents
• Number Helper
– Loading this Helper
– byte_format()
244
Chapter 9.
CodeIgniter Documentation, 3.0-dev
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’number’);
The following functions are available:
byte_format()
byte_format($num, $precision = 1)
• $num (mixed) – Number of bytes
• $precision (int) – Floating point precision
string
Formats numbers as bytes, based on size, and adds the appropriate suffix. Examples:
echo
echo
echo
echo
echo
echo
echo
byte_format(456); // Returns 456 Bytes
byte_format(4567); // Returns 4.5 KB
byte_format(45678); // Returns 44.6 KB
byte_format(456789); // Returns 447.8 KB
byte_format(3456789); // Returns 3.3 MB
byte_format(12345678912345); // Returns 1.8 GB
byte_format(123456789123456789); // Returns 11,228.3 TB
An optional second parameter allows you to set the precision of the result:
echo byte_format(45678, 2); // Returns 44.61 KB
: The text generated by this function is found in the following language file: language/<your_lang>/number_lang.php
9.1.14 Path Helper
The Path Helper file contains functions that permits you to work with file paths on the server.
Page Contents
• Path Helper
– Loading this Helper
– set_realpath()
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’path’);
The following functions are available:
9.1. Helpers
245
CodeIgniter Documentation, 3.0-dev
set_realpath()
set_realpath($path, $check_existance = FALSE)
• $path (string) – Path
• $check_existance (bool) – Whether to check if the path actually exists
string
This function will return a server path without symbolic links or relative directory structures. An optional second
argument will cause an error to be triggered if the path cannot be resolved.
Examples:
$file = ’/etc/php5/apache2/php.ini’;
echo set_realpath($file); // Prints ’/etc/php5/apache2/php.ini’
$non_existent_file = ’/path/to/non-exist-file.txt’;
echo set_realpath($non_existent_file, TRUE);
// Shows an error, as the path cannot be resolved
echo set_realpath($non_existent_file, FALSE);
// Prints ’/path/to/non-exist-file.txt’
$directory = ’/etc/php5’;
echo set_realpath($directory);
// Prints ’/etc/php5/’
$non_existent_directory = ’/path/to/nowhere’;
echo set_realpath($non_existent_directory, TRUE);
echo set_realpath($non_existent_directory, FALSE);
// Shows an error, as the path cannot be reso
// Prints ’/path/to/nowhere’
9.1.15 Security Helper
The Security Helper file contains security related functions.
Page Contents
• Security Helper
– Loading this Helper
– xss_clean()
– sanitize_filename()
– do_hash()
– strip_image_tags()
– encode_php_tags()
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’security’);
The following functions are available:
246
Chapter 9.
CodeIgniter Documentation, 3.0-dev
xss_clean()
xss_clean($str, $is_image = FALSE)
• $str (string) – Input data
• $is_image (bool) – Whether we’re dealing with an image
string
Provides Cross Site Script Hack filtering.
This function is an alias for CI_Input::xss_clean(). For more info, please see the Input Library documentation.
sanitize_filename()
sanitize_filename($filename)
• $filename (string) – Filename
string
Provides protection against directory traversal.
This function is an alias for CI_Security::sanitize_filename(). For more info, please see the Security
Library documentation.
do_hash()
do_hash($str, $type = ‘sha1’)
• $str (string) – Input
• $type (string) – Algorithm
string
Permits you to create one way hashes suitable for encrypting passwords. Will use SHA1 by default.
See hash_algos() for a full list of supported algorithms.
Examples:
$str = do_hash($str); // SHA1
$str = do_hash($str, ’md5’); // MD5
: This function was formerly named dohash(), which has been removed in favor of do_hash().
: This function is DEPRECATED. Use the native hash() instead.
9.1. Helpers
247
CodeIgniter Documentation, 3.0-dev
strip_image_tags()
strip_image_tags($str)
• $str (string) – Input
string
This is a security function that will strip image tags from a string. It leaves the image URL as plain text.
Example:
$string = strip_image_tags($string);
This function is an alias for CI_Security::strip_image_tags(). For more info, please see the Security
Library documentation.
encode_php_tags()
encode_php_tags($str)
• $str (string) – Input
string
This is a security function that converts PHP tags to entities.
Example:
$string = encode_php_tags($string);
9.1.16 Smiley Helper
The Smiley Helper file contains functions that let you manage smileys (emoticons).
Page Contents
• Smiley Helper
– Loading this Helper
– Overview
– Clickable Smileys Tutorial
* The Controller
* Field Aliases
– get_clickable_smileys()
– smiley_js()
– parse_smileys()
Loading this Helper
This helper is loaded using the following code:
248
Chapter 9.
CodeIgniter Documentation, 3.0-dev
$this->load->helper(’smiley’);
Overview
The Smiley helper has a renderer that takes plain text smileys, like :-) and turns them into a image representation, like
It also lets you display a set of smiley images that when clicked will be inserted into a form field. For example, if you
have a blog that allows user commenting you can show the smileys next to the comment form. Your users can click a
desired smiley and with the help of some JavaScript it will be placed into the form field.
Clickable Smileys Tutorial
Here is an example demonstrating how you might create a set of clickable smileys next to a form field. This example
requires that you first download and install the smiley images, then create a controller and the View as described.
: Before you begin, please download the smiley images and put them in a publicly accessible place on your server.
This helper also assumes you have the smiley replacement array located at application/config/smileys.php
The Controller
In your application/controllers/ directory, create a file called Smileys.php and place the code below in it.
: Change the URL in the get_clickable_smileys() function below so that it points to your smiley folder.
You’ll notice that in addition to the smiley helper, we are also using the Table Class:
<?php
class Smileys extends CI_Controller {
public function index()
{
$this->load->helper(’smiley’);
$this->load->library(’table’);
$image_array = get_clickable_smileys(’http://example.com/images/smileys/’, ’comments’
$col_array = $this->table->make_columns($image_array, 8);
$data[’smiley_table’] = $this->table->generate($col_array);
$this->load->view(’smiley_view’, $data);
}
}
In your application/views/ folder, create a file called smiley_view.php and place this code in it:
<html>
<head>
<title>Smileys</title>
<?php echo smiley_js(); ?>
</head>
<body>
<form name="blog">
9.1. Helpers
249
CodeIgniter Documentation, 3.0-dev
<textarea name="comments" id="comments" cols="40" rows="4"></textarea>
</form>
<p>Click to insert a smiley!</p>
<?php echo $smiley_table; ?> </body> </html>
When you have created the above controller and view, load it by visiting http://www.e
</body>
</html>
Field Aliases
When making changes to a view it can be inconvenient to have the field id in the controller. To work around this, you
can give your smiley links a generic name that will be tied to a specific id in your view.
$image_array = get_smiley_links("http://example.com/images/smileys/", "comment_textarea_alias");
To map the alias to the field id, pass them both into the smiley_js() function:
$image_array = smiley_js("comment_textarea_alias", "comments");
get_clickable_smileys()
get_clickable_smileys($image_url, $alias = ‘’, $smileys = NULL)
• $image_url (string) – URL path to the smileys directory
• $alias (string) – Field alias
array
Returns an array containing your smiley images wrapped in a clickable link. You must supply the URL to your smiley
folder and a field id or field alias.
Example:
$image_array = get_smiley_links("http://example.com/images/smileys/", "comment");
smiley_js()
smiley_js($alias = ‘’, $field_id = ‘’, $inline = TRUE)
• $alias (string) – Field alias
• $field_id (string) – Field ID
• $inline (bool) – Whether we’re inserting an inline smiley
Generates the JavaScript that allows the images to be clicked and inserted into a form field. If you supplied an alias
instead of an id when generating your smiley links, you need to pass the alias and corresponding form id into the
function. This function is designed to be placed into the <head> area of your web page.
Example:
<?php echo smiley_js(); ?>
250
Chapter 9.
CodeIgniter Documentation, 3.0-dev
parse_smileys()
parse_smileys($str = ‘’, $image_url = ‘’, $smileys = NULL)
• $str (string) – Text containing smiley codes
• $image_url (string) – URL path to the smileys directory
• $smileys (array) – An array of smileys
string
Takes a string of text as input and replaces any contained plain text smileys into the image equivalent. The first
parameter must contain your string, the second must contain the URL to your smiley folder
Example:
$str = ’Here are some smileys: :-) ;-)’;
$str = parse_smileys($str, "http://example.com/images/smileys/");
echo $str;
9.1.17 String Helper
The String Helper file contains functions that assist in working with strings.
Page Contents
• String Helper
– Loading this Helper
– random_string()
– increment_string()
– alternator()
– repeater()
– reduce_double_slashes()
– strip_slashes()
– trim_slashes()
– reduce_multiples()
– quotes_to_entities()
– strip_quotes()
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’string’);
The following functions are available:
random_string()
random_string($type = ‘alnum’, $len = 8)
9.1. Helpers
251
CodeIgniter Documentation, 3.0-dev
• $type (string) – Randomization type
• $len (int) – Output string length
string
Generates a random string based on the type and length you specify. Useful for creating passwords or generating
random hashes.
The first parameter specifies the type of string, the second parameter specifies the length. The following choices are
available:
• alpha: A string with lower and uppercase letters only.
• alnum: Alpha-numeric string with lower and uppercase characters.
• basic: A random number based on mt_rand().
• numeric: Numeric string.
• nozero: Numeric string with no zeros.
• md5: An encrypted random number based on md5() (fixed length of 32).
• sha1: An encrypted random number based on sha1() (fixed length of 40).
Usage example:
echo random_string(’alnum’, 16);
: Usage of the unique and encrypt types is DEPRECATED. They are just aliases for md5 and sha1 respectively.
increment_string()
increment_string($str, $separator = ‘_’, $first = 1)
• $str (string) – Input string
• $separator (string) – Separator to append a duplicate number with
• $first (int) – Starting number
string
Increments a string by appending a number to it or increasing the number. Useful for creating “copies” or a file or
duplicating database content which has unique titles or slugs.
Usage example:
echo increment_string(’file’, ’_’); // "file_1"
echo increment_string(’file’, ’-’, 2); // "file-2"
echo increment_string(’file_4’); // "file_5"
alternator()
alternator($args)
• $args (mixed) – A variable number of arguments
252
Chapter 9.
CodeIgniter Documentation, 3.0-dev
mixed
Allows two or more items to be alternated between, when cycling through a loop. Example:
for ($i = 0; $i < 10; $i++)
{
echo alternator(’string one’, ’string two’);
}
You can add as many parameters as you want, and with each iteration of your loop the next item will be returned.
for ($i = 0; $i < 10; $i++)
{
echo alternator(’one’, ’two’, ’three’, ’four’, ’five’);
}
: To use multiple separate calls to this function simply call the function with no arguments to re-initialize.
repeater()
repeater($data, $num = 1)
• $data (string) – Input
• $num (int) – Number of times to repeat
string
Generates repeating copies of the data you submit. Example:
$string = "\n";
echo repeater($string, 30);
The above would generate 30 newlines.
: This function is DEPRECATED. Use the native str_repeat() instead.
reduce_double_slashes()
reduce_double_slashes($str)
• $str (string) – Input string
string
Converts double slashes in a string to a single slash, except those found in URL protocol prefixes (e.g. http://).
Example:
$string = "http://example.com//index.php";
echo reduce_double_slashes($string); // results in "http://example.com/index.php"
9.1. Helpers
253
CodeIgniter Documentation, 3.0-dev
strip_slashes()
strip_slashes($data)
• $data (array) – Input
array
Removes any slashes from an array of strings.
Example:
$str = array(
’question’ => ’Is your name O\’reilly?’,
’answer’ => ’No, my name is O\’connor.’
);
$str = strip_slashes($str);
The above will return the following array:
array(
’question’ => "Is your name O’reilly?",
’answer’ => "No, my name is O’connor."
);
: For historical reasons, this function will also accept and handle string inputs. This however makes it just an alias
for stripslashes().
trim_slashes()
trim_slashes($str)
• $str (string) – Input string
string
Removes any leading/trailing slashes from a string. Example:
$string = "/this/that/theother/";
echo trim_slashes($string); // results in this/that/theother
: This function is DEPRECATED. Use the native trim() instead: | | trim($str, ‘/’);
reduce_multiples()
reduce_multiples($str, $character = ‘’, $trim = FALSE)
• $str (string) – Text to search in
• $character (string) – Character to reduce
• $trim (bool) – Whether to also trim the specified character
254
Chapter 9.
CodeIgniter Documentation, 3.0-dev
string
Reduces multiple instances of a particular character occuring directly after each other. Example:
$string = "Fred, Bill,, Joe, Jimmy";
$string = reduce_multiples($string,","); //results in "Fred, Bill, Joe, Jimmy"
If the third parameter is set to TRUE it will remove occurences of the character at the beginning and the end of the
string. Example:
$string = ",Fred, Bill,, Joe, Jimmy,";
$string = reduce_multiples($string, ", ", TRUE); //results in "Fred, Bill, Joe, Jimmy"
quotes_to_entities()
quotes_to_entities($str)
• $str (string) – Input string
string
Converts single and double quotes in a string to the corresponding HTML entities. Example:
$string = "Joe’s \"dinner\"";
$string = quotes_to_entities($string); //results in "Joe&#39;s &quot;dinner&quot;"
strip_quotes()
strip_quotes($str)
• $str (string) – Input string
string
Removes single and double quotes from a string. Example:
$string = "Joe’s \"dinner\"";
$string = strip_quotes($string); //results in "Joes dinner"
9.1.18 Text Helper
The Text Helper file contains functions that assist in working with text.
9.1. Helpers
255
CodeIgniter Documentation, 3.0-dev
Page Contents
• Text Helper
– Loading this Helper
– word_limiter()
– character_limiter()
– ascii_to_entities()
– entities_to_ascii()
– convert_accented_characters()
– word_censor()
– highlight_code()
– highlight_phrase()
– word_wrap()
– ellipsize()
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’text’);
The following functions are available:
word_limiter()
word_limiter($str, $limit = 100, $end_char = ‘&#8230;’)
• $str (string) – Input string
• $limit (int) – Limit
• $end_char (string) – End character (usually an ellipsis)
string
Truncates a string to the number of words specified. Example:
$string = "Here is a nice text string consisting of eleven words.";
$string = word_limiter($string, 4);
// Returns: Here is a nice...
The third parameter is an optional suffix added to the string. By default it adds an ellipsis.
character_limiter()
character_limiter($str, $n = 500, $end_char = ‘&#8230;’)
• $str (string) – Input string
• $n (int) – Number of characters
• $end_char (string) – End character (usually an ellipsis)
string
256
Chapter 9.
CodeIgniter Documentation, 3.0-dev
Truncates a string to the number of characters specified. It maintains the integrity of words so the character count may
be slightly more or less then what you specify.
Example:
$string = "Here is a nice text string consisting of eleven words.";
$string = character_limiter($string, 20);
// Returns: Here is a nice text string...
The third parameter is an optional suffix added to the string, if undeclared this helper uses an ellipsis.
: If you need to truncate to an exact number of characters please see the ellipsize() function below.
ascii_to_entities()
ascii_to_entities($str)
• $str (string) – Input string
string
Converts ASCII values to character entities, including high ASCII and MS Word characters that can cause problems
when used in a web page, so that they can be shown consistently regardless of browser settings or stored reliably in a
database. There is some dependence on your server’s supported character sets, so it may not be 100% reliable in all
cases, but for the most part it should correctly identify characters outside the normal range (like accented characters).
Example:
$string = ascii_to_entities($string);
entities_to_ascii()
This function does the opposite of ascii_to_entities(). It turns character entities back into ASCII.
convert_accented_characters()
convert_accented_characters($str)
• $str (string) – Input string
string
Transliterates high ASCII characters to low ASCII equivalents. Useful when non-English characters need to be used
where only standard ASCII characters are safely used, for instance, in URLs.
Example:
$string = convert_accented_characters($string);
: This function uses a companion config file application/config/foreign_chars.php to define the to and from array for
transliteration.
9.1. Helpers
257
CodeIgniter Documentation, 3.0-dev
word_censor()
word_censor($str, $censored, $replacement = ‘’)
• $str (string) – Input string
• $censored (array) – List of bad words to censor
• $replacement (string) – What to replace bad words with
string
Enables you to censor words within a text string. The first parameter will contain the original string. The second will
contain an array of words which you disallow. The third (optional) parameter can contain a replacement value for the
words. If not specified they are replaced with pound signs: ####.
Example:
$disallowed = array(’darn’, ’shucks’, ’golly’, ’phooey’);
$string = word_censor($string, $disallowed, ’Beep!’);
highlight_code()
highlight_code($str)
• $str (string) – Input string
string
Colorizes a string of code (PHP, HTML, etc.). Example:
$string = highlight_code($string);
The function uses PHP’s highlight_string() function, so the colors used are the ones specified in your php.ini
file.
highlight_phrase()
highlight_phrase($str, $phrase, $tag_open = ‘<strong>’, $tag_close = ‘</strong>’)
• $str (string) – Input string
• $phrase (string) – Phrase to highlight
• $tag_open (string) – Opening tag used for the highlight
• $tag_close (string) – Closing tag for the highlight
string
Will highlight a phrase within a text string. The first parameter will contain the original string, the second will contain
the phrase you wish to highlight. The third and fourth parameters will contain the opening/closing HTML tags you
would like the phrase wrapped in.
Example:
258
Chapter 9.
CodeIgniter Documentation, 3.0-dev
$string = "Here is a nice text string about nothing in particular.";
echo highlight_phrase($string, "nice text", ’<span style="color:#990000;">’, ’</span>’);
The above code prints:
Here is a <span style="color:#990000;">nice text</span> string about nothing in particular.
word_wrap()
word_wrap($str, $charlim = 76)
• $str (string) – Input string
• $charlim (int) – Character limit
string
Wraps text at the specified character count while maintaining complete words.
Example:
$string = "Here is a simple string of text that will help us demonstrate this function.";
echo word_wrap($string, 25);
// Would produce:
Here is a simple string of text that will help us demonstrate this function
ellipsize()
ellipsize($str, $max_length, $position = 1, $ellipsis = ‘&hellip;’)
• $str (string) – Input string
• $max_length (int) – String length limit
• $position (mixed) – Position to split at (int or float)
• $ellipsis (string) – What to use as the ellipsis character
string
This function will strip tags from a string, split it at a defined maximum length, and insert an ellipsis.
The first parameter is the string to ellipsize, the second is the number of characters in the final string. The third
parameter is where in the string the ellipsis should appear from 0 - 1, left to right. For example. a value of 1 will place
the ellipsis at the right of the string, .5 in the middle, and 0 at the left.
An optional forth parameter is the kind of ellipsis. By default, &hellip; will be inserted.
Example:
$str = ’this_string_is_entirely_too_long_and_might_break_my_design.jpg’;
echo ellipsize($str, 32, .5);
Produces:
this_string_is_e&hellip;ak_my_design.jpg
9.1. Helpers
259
CodeIgniter Documentation, 3.0-dev
9.1.19 Typography Helper
The Typography Helper file contains functions that help your format text in semantically relevant ways.
Page Contents
• Typography Helper
– Loading this Helper
– auto_typography()
– nl2br_except_pre()
– entity_decode()
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’typography’);
The following functions are available:
auto_typography()
auto_typography($str, $reduce_linebreaks = FALSE)
• $str (string) – Input string
• $reduce_linebreaks (bool) – Whether to reduce multiple instances of double newlines to
two
string
Formats text so that it is semantically and typographically correct HTML.
This function is an alias for CI_Typography::auto_typography. For more info, please see the Typography
Library documentation.
Usage example:
$string = auto_typography($string);
: Typographic formatting can be processor intensive, particularly if you have a lot of content being formatted. If you
choose to use this function you may want to consider caching <../general/caching> your pages.
nl2br_except_pre()
nl2br_except_pre($str)
• $str (string) – Input string
string
260
Chapter 9.
CodeIgniter Documentation, 3.0-dev
Converts newlines to <br /> tags unless they appear within <pre> tags. This function is identical to the native PHP
nl2br() function, except that it ignores <pre> tags.
Usage example:
$string = nl2br_except_pre($string);
entity_decode()
entity_decode($str, $charset = NULL)
• $str (string) – Input string
• $charset (string) – Character set
string
This function is an alias for CI_Security::entity_decode(). Fore more info, please see the Security Library
documentation.
9.1.20 URL Helper
The URL Helper file contains functions that assist in working with URLs.
Page Contents
• URL Helper
– Loading this Helper
– site_url()
– base_url()
– current_url()
– uri_string()
– index_page()
– anchor()
– anchor_popup()
– mailto()
– safe_mailto()
– auto_link()
– url_title()
* prep_url()
– redirect()
Loading this Helper
This helper is loaded using the following code:
$this->load->helper(’url’);
The following functions are available:
9.1. Helpers
261
CodeIgniter Documentation, 3.0-dev
site_url()
site_url($uri = ‘’, $protocol = NULL)
• $uri (string) – URI string
• $protocol (string) – Protocol, e.g. ‘http’ or ‘https’
string
Returns your site URL, as specified in your config file. The index.php file (or whatever you have set as your site
index_page in your config file) will be added to the URL, as will any URI segments you pass to the function, plus the
url_suffix as set in your config file.
You are encouraged to use this function any time you need to generate a local URL so that your pages become more
portable in the event your URL changes.
Segments can be optionally passed to the function as a string or an array. Here is a string example:
echo site_url(’news/local/123’);
The above example would return something like: http://example.com/index.php/news/local/123
Here is an example of segments passed as an array:
$segments = array(’news’, ’local’, ’123’);
echo site_url($segments);
This function is an alias for CI_Config::site_url(). For more info, please see the Config Library documentation.
base_url()
base_url($uri = ‘’, $protocol = NULL)
• $uri (string) – URI string
• $protocol (string) – Protocol, e.g. ‘http’ or ‘https’
string
Returns your site base URL, as specified in your config file. Example:
echo base_url();
This function returns the same thing as site_url(), without the index_page or url_suffix being appended.
Also like site_url(), you can supply segments as a string or an array. Here is a string example:
echo base_url("blog/post/123");
The above example would return something like: http://example.com/blog/post/123
This is useful because unlike site_url(), you can supply a string to a file, such as an image or stylesheet. For
example:
echo base_url("images/icons/edit.png");
262
Chapter 9.
CodeIgniter Documentation, 3.0-dev
This would give you something like: http://example.com/images/icons/edit.png
This function is an alias for CI_Config::base_url(). For more info, please see the Config Library documentation.
current_url()
current_url()
string
Returns the full URL (including segments) of the page being currently viewed.
: Calling this function is the same as doing this: | | site_url(uri_string());
uri_string()
uri_string()
string
Returns the URI segments of any page that contains this function. For example, if your URL was this:
http://some-site.com/blog/comments/123
The function would return:
blog/comments/123
This function is an alias for CI_Config::uri_string(). For more info, please see the Config Library documentation.
index_page()
index_page()
string
Returns your site index_page, as specified in your config file. Example:
echo index_page();
anchor()
anchor($uri = ‘’, $title = ‘’, $attributes = ‘’)
• $uri (string) – URI string
• $title (string) – Anchor title
• $attributes (mixed) – HTML attributes
string
9.1. Helpers
263
CodeIgniter Documentation, 3.0-dev
Creates a standard HTML anchor link based on your local site URL.
The first parameter can contain any segments you wish appended to the URL. As with the site_url() function
above, segments can be a string or an array.
: If you are building links that are internal to your application do not include the base URL (http://...). This will
be added automatically from the information specified in your config file. Include only the URI segments you wish
appended to the URL.
The second segment is the text you would like the link to say. If you leave it blank, the URL will be used.
The third parameter can contain a list of attributes you would like added to the link. The attributes can be a simple
string or an associative array.
Here are some examples:
echo anchor(’news/local/123’, ’My News’, ’title="News title"’);
// Prints: <a href="http://example.com/index.php/news/local/123" title="News title">My News</a>
echo anchor(’news/local/123’, ’My News’, array(’title’ => ’The best news!’));
// Prints: <a href="http://example.com/index.php/news/local/123" title="The best news!">My News</a>
echo anchor(’’, ’Click here’);
// Prints: <a href="http://example.com">Click Here</a>
anchor_popup()
anchor_popup($uri = ‘’, $title = ‘’, $attributes = FALSE)
• $uri (string) – URI string
• $title (string) – Anchor title
• $attributes (mixed) – HTML attributes
string
Nearly identical to the :php:func:anchor() function except that it opens the URL in a new window. You can specify
JavaScript window attributes in the third parameter to control how the window is opened. If the third parameter is not
set it will simply open a new window with your own browser settings.
Here is an example with attributes:
$atts = array(
’width’
’height’
’scrollbars’
’status’
’resizable’
’screenx’
’screeny’
’window_name’
);
=>
=>
=>
=>
=>
=>
=>
=>
800,
600,
’yes’,
’yes’,
’yes’,
0,
0,
’_blank’
echo anchor_popup(’news/local/123’, ’Click Me!’, $atts);
: The above attributes are the function defaults so you only need to set the ones that are different from what you
264
Chapter 9.
CodeIgniter Documentation, 3.0-dev
need. If you want the function to use all of its defaults simply pass an empty array in the third parameter: | | echo
anchor_popup(‘news/local/123’, ‘Click Me!’, array());
:
The window_name is not really an attribute, but an argument to the JavaScript window.open()
<http://www.w3schools.com/jsref/met_win_open.asp> method, which accepts either a window name or a window
target.
: Any other attribute than the listed above will be parsed as an HTML attribute to the anchor tag.
mailto()
mailto($email, $title = ‘’, $attributes = ‘’)
• $email (string) – E-mail address
• $title (string) – Anchor title
• $attributes (mixed) – HTML attributes
string
Creates a standard HTML e-mail link. Usage example:
echo mailto(’me@my-site.com’, ’Click Here to Contact Me’);
As with the anchor() tab above, you can set attributes using the third parameter:
$attributes = array(’title’ => ’Mail me’);
echo mailto(’me@my-site.com’, ’Contact Me’, $attributes);
safe_mailto()
safe_mailto($email, $title = ‘’, $attributes = ‘’)
• $email (string) – E-mail address
• $title (string) – Anchor title
• $attributes (mixed) – HTML attributes
string
Identical to the mailto() function except it writes an obfuscated version of the mailto tag using ordinal numbers
written with JavaScript to help prevent the e-mail address from being harvested by spam bots.
auto_link()
auto_link($str, $type = ‘both’, $popup = FALSE)
• $str (string) – Input string
• $type (string) – Link type (‘email’, ‘url’ or ‘both’)
9.1. Helpers
265
CodeIgniter Documentation, 3.0-dev
• $popup (bool) – Whether to create popup links
string
Automatically turns URLs and e-mail addresses contained in a string into links. Example:
$string = auto_link($string);
The second parameter determines whether URLs and e-mails are converted or just one or the other. Default behavior
is both if the parameter is not specified. E-mail links are encoded as safe_mailto() as shown above.
Converts only URLs:
$string = auto_link($string, ’url’);
Converts only e-mail addresses:
$string = auto_link($string, ’email’);
The third parameter determines whether links are shown in a new window. The value can be TRUE or FALSE
(boolean):
$string = auto_link($string, ’both’, TRUE);
url_title()
url_title($str, $separator = ‘-‘, $lowercase = FALSE)
• $str (string) – Input string
• $separator (string) – Word separator
• $lowercase (string) – Whether to transform the output string to lower-case
string
Takes a string as input and creates a human-friendly URL string. This is useful if, for example, you have a blog in
which you’d like to use the title of your entries in the URL. Example:
$title = "What’s wrong with CSS?";
$url_title = url_title($title);
// Produces: Whats-wrong-with-CSS
The second parameter determines the word delimiter. By default dashes are used. Preferred options are: - (dash) or _
(underscore)
Example:
$title = "What’s wrong with CSS?";
$url_title = url_title($title, ’underscore’);
// Produces: Whats_wrong_with_CSS
: Old usage of ‘dash’ and ‘underscore’ as the second parameter is DEPRECATED.
The third parameter determines whether or not lowercase characters are forced. By default they are not. Options are
boolean TRUE/FALSE.
Example:
266
Chapter 9.
CodeIgniter Documentation, 3.0-dev
$title = "What’s wrong with CSS?";
$url_title = url_title($title, ’underscore’, TRUE);
// Produces: whats_wrong_with_css
prep_url()
prep_url($str = ‘’)
• $str (string) – URL string
string
This function will add http:// in the event that a protocol prefix is missing from a URL.
Pass the URL string to the function like this:
$url = prep_url(’example.com’);
redirect()
redirect($uri = ‘’, $method = ‘auto’, $code = NULL)
• $uri (string) – URI string
• $method (string) – Redirect method (‘auto’, ‘location’ or ‘refresh’)
• $code (string) – HTTP Response code (usually 302 or 303)
void
Does a “header redirect” to the URI specified. If you specify the full site URL that link will be built, but for local links
simply providing the URI segments to the controller you want to direct to will create the link. The function will build
the URL based on your config file values.
The optional second parameter allows you to force a particular redirection method. The available methods are auto,
location and refresh, with location being faster but less reliable on IIS servers. The default is auto, which will attempt
to intelligently choose the method based on the server environment.
The optional third parameter allows you to send a specific HTTP Response Code - this could be used for example
to create 301 redirects for search engine purposes. The default Response Code is 302. The third parameter is only
available with location redirects, and not refresh. Examples:
if ($logged_in == FALSE)
{
redirect(’/login/form/’);
}
// with 301 redirect
redirect(’/article/13’, ’location’, 301);
: In order for this function to work it must be used before anything is outputted to the browser since it utilizes server
headers.
: For very fine grained control over headers, you should use the Output Library </libraries/output> set_header()
method.
9.1. Helpers
267
CodeIgniter Documentation, 3.0-dev
: To IIS users: if you hide the Server HTTP header, the auto method won’t detect IIS, in that case it is advised you
explicitly use the refresh method.
: When the location method is used, an HTTP status code of 303 will automatically be selected when the page is
currently accessed via POST and HTTP/1.1 is used.
: This function will terminate script execution.
9.1.21 XML Helper
The XML Helper file contains functions that assist in working with XML data.
Page Contents
• XML Helper
– Loading this Helper
– xml_convert()
Loading this Helper
This helper is loaded using the following code
$this->load->helper(’xml’);
The following functions are available:
xml_convert()
Takes a string as input and converts the following reserved XML characters to entities:
• Ampersands: &
• Less then and greater than characters: < >
• Single and double quotes: ‘ “
• Dashes: This function ignores ampersands if they are part of existing character entities. Example
$string = xml_convert($string);
268
Chapter 9.
CHAPTER 10
CodeIgniter
10.1 Contributing to CodeIgniter
CodeIgniter is a community driven project and accepts contributions of code and documentation from the community.
These contributions are made in the form of Issues or Pull Requests on the EllisLab CodeIgniter repository on GitHub.
Issues are a quick way to point out a bug. If you find a bug or documentation error in CodeIgniter then please check a
few things first:
• There is not already an open Issue
• The issue has already been fixed (check the develop branch, or look for closed Issues)
• Is it something really obvious that you fix it yourself?
Reporting issues is helpful but an even better approach is to send a Pull Request, which is done by “Forking” the main
repository and committing to your own copy. This will require you to use the version control system called Git.
10.1.1 Guidelines
Before we look into how, here are the guidelines. If your Pull Requests fail to pass these guidelines it will be declined
and you will need to re-submit when you’ve made the changes. This might sound a bit tough, but it is required for us
to maintain quality of the code-base.
PHP Style
All code must meet the Style Guide, which is essentially the Allman indent style, underscores and readable operators.
This makes certain that all code is the same format as the existing code and means it will be as readable as possible.
Documentation
If you change anything that requires a change to documentation then you will need to add it. New classes, methods,
parameters, changing default values, etc are all things that will require a change to documentation. The change-log
must also be updated for every change. Also PHPDoc blocks must be maintained.
Compatibility
CodeIgniter is compatible with PHP 5.2.4 so all code supplied must stick to this requirement. If PHP 5.3 or 5.4
functions or features are used then there must be a fallback for PHP 5.2.4.
269
CodeIgniter Documentation, 3.0-dev
Branching
CodeIgniter uses the Git-Flow branching model which requires all pull requests to be sent to the “develop” branch.
This is where the next planned version will be developed. The “master” branch will always contain the latest stable
version and is kept clean so a “hotfix” (e.g: an emergency security patch) can be applied to master to create a new
version, without worrying about other features holding it up. For this reason all commits need to be made to “develop”
and any sent to “master” will be closed automatically. If you have multiple changes to submit, please place all changes
into their own branch on your fork.
One thing at a time: A pull request should only contain one change. That does not mean only one commit, but one
change - however many commits it took. The reason for this is that if you change X and Y but send a pull request for
both at the same time, we might really want X but disagree with Y, meaning we cannot merge the request. Using the
Git-Flow branching model you can create new branches for both of these features and send two requests.
Signing
You must sign your work, certifying that you either wrote the work or otherwise have the right to pass it on to an open
source project. git makes this trivial as you merely have to use –signoff on your commits to your CodeIgniter fork.
git commit --signoff
or simply
git commit -s
This will sign your commits with the information setup in your git config, e.g.
Signed-off-by: John Q Public <john.public@example.com>
If you are using Tower there is a “Sign-Off” checkbox in the commit window. You could even alias git commit to use
the -s flag so you don’t have to think about it.
By signing your work in this manner, you certify to a “Developer’s Certificate or Origin”. The current version of this
certificate is in the Developer’s Certificate of Origin 1.1 file in the root of this documentation.
10.2 Developer’s Certificate of Origin 1.1
By making a contribution to this project, I certify that:
1. The contribution was created in whole or in part by me and I have the right to submit it under the open source
license indicated in the file; or
2. The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate
open source license and I have the right under that license to submit that work with modifications, whether
created in whole or in part by me, under the same open source license (unless I am permitted to submit under a
different license), as indicated in the file; or
3. The contribution was provided directly to me by some other person who certified (1), (2) or (3) and I have not
modified it.
4. I understand and agree that this project and the contribution are public and that a record of the contribution
(including all personal information I submit with it, including my sign-off) is maintained indefinitely and may
be redistributed consistent with this project or the open source license(s) involved.
270
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
10.3 Developer’s Certificate of Origin 1.1
By making a contribution to this project, I certify that:
1. The contribution was created in whole or in part by me and I have the right to submit it under the open source
license indicated in the file; or
2. The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate
open source license and I have the right under that license to submit that work with modifications, whether
created in whole or in part by me, under the same open source license (unless I am permitted to submit under a
different license), as indicated in the file; or
3. The contribution was provided directly to me by some other person who certified (1), (2) or (3) and I have not
modified it.
4. I understand and agree that this project and the contribution are public and that a record of the contribution
(including all personal information I submit with it, including my sign-off) is maintained indefinitely and may
be redistributed consistent with this project or the open source license(s) involved.
10.4 CodeIgniter 3.0 Dev
CodeIgniter 3.0
10.4.1
CodeIgniterSphinx ReStructured Text
SphinxPython(OS X) python 2.7+ , http://python.org/download/releases/2.7.2/ 2.7.2
1. Install easy_install
2. easy_install sphinx
3. easy_install sphinxcontrib-phpdomain
4. Install the CI Lexer which allows PHP, HTML, CSS, and JavaScript syntax highlighting in code examples (see
cilexer/README)
5. cd user_guide_src
6. make html
source/ PR develop
10.3. Developer’s Certificate of Origin 1.1
271
CodeIgniter Documentation, 3.0-dev
HTML?
HTML “” HTML Repo:
make html
build/html HTML “” build
10.4.2
source/documentation/index.rst SphinxCodeIgniter
10.5 Change Log
10.5.1 Version 3.0 (planned)
Release Date: Not Released
• License
– CodeIgniter has been relicensed with the Open Software License (3.0), eliminating its old proprietary
licensing.
* All system files are licensed with OSL 3.0.
* Config, error, and sample files shipped in the application folder are licensed with the Academic Free
License (3.0) to allow you to retain all licensing authority over your own application code.
• General Changes
– PHP 5.1.6 is no longer supported. CodeIgniter now requires PHP 5.2.4.
– Changed filenaming convention (class file names now must be Ucfirst and everything else in lowercase).
– $_SERVER[’CI_ENV’] can now be set to control the ENVIRONMENT constant.
– Added an optional backtrace to php-error template.
– Added Android to the list of user agents.
– Added Windows 7, Windows 8, Android, Blackberry, iOS and PlayStation 3 to the list of user platforms.
– Added Fennec (Firefox for mobile) to the list of mobile user agents.
– Ability to log certain error types, not all under a threshold.
– Added support for pem, p10, p12, p7a, p7c, p7m, p7r, p7s, crt, crl, der, kdb, rsa, cer, sst, csr Certs to
mimes.php.
– Added support for pgp, gpg, zsh and cdr files to mimes.php.
– Added support for 3gp, 3g2, mp4, wmv, f4v, vlc Video files to mimes.php.
– Added support for m4a, aac, m4u, xspf, au, ac3, flac, ogg, wma Audio files to mimes.php.
– Added support for kmz and kml (Google Earth) files to mimes.php.
– Added support for ics Calendar files to mimes.php.
– Added support for rar, jar and 7zip archives to mimes.php.
– Updated support for xml (‘application/xml’) and xsl (‘application/xml’, ‘text/xsl’) files in mimes.php.
272
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
– Updated support for doc files in mimes.php.
– Updated support for docx files in mimes.php.
– Updated support for php files in mimes.php.
– Updated support for zip files in mimes.php.
– Updated support for csv files in mimes.php.
– Added Romanian, Greek, Vietnamese and Cyrilic characters in application/config/foreign_characters.php.
– Changed logger to only chmod when file is first created.
– Removed previously deprecated SHA1 Library.
– Removed previously deprecated use of $autoload[’core’] in application/config/autoload.php. Only
entries in $autoload[’libraries’] are auto-loaded now.
– Removed previously deprecated EXT constant.
– Updated all classes to be written in PHP 5 style, with visibility declarations and no var usage for properties.
– Moved error templates to application/views/errors/.
– Moved the Log class to application/core/
– Global config files are loaded first, then environment ones. Environment config keys overwrite base ones,
allowing to only set the keys we want changed per environment.
– Changed detection of $view_folder so that if it’s not found in the current path, it will now also be
searched for under the application folder.
– Path constants BASEPATH, APPPATH and VIEWPATH are now (internally) defined as absolute paths.
– Updated email validation methods to use filter_var() instead of PCRE.
– Changed environment defaults to report all errors in development and only fatal ones in testing, production
but only display them in development.
– Updated ip_address database field lengths from 16 to 45 for supporting IPv6 address on Trackback Library
and Captcha Helper.
– Removed cheatsheets and quick_reference PDFs from the documentation.
– Added support non-HTML error templates for CLI applications.
– Added availability checks where usage of dangerous functions like eval() and exec() is required.
– Added
support
for
changing
the
$config[’log_file_extension’].
file
extension
of
log
files
using
• Helpers
– Date Helper changes include:
* now() now works with all timezone strings supported by PHP.
* Added an optional third parameter to timespan() that constrains the number of time units displayed.
* Added an optional parameter to timezone_menu() that allows more attributes to be added to the
generated select tag.
* Deprecated standard_date(), which now just uses the native date() with DateTime constants.
* Added function date_range() that generates a list of dates between a specified period.
10.5. Change Log
273
CodeIgniter Documentation, 3.0-dev
– URL Helper changes include:
* Deprecated separator options dash and underscore for function url_title() (they are only
aliases for ‘-‘ and ‘_’ respectively).
* url_title() will now trim extra dashes from beginning and end.
* anchor_popup() will now fill the href attribute with the URL and its JS code will return FALSE
instead.
* Added JS window name support to the anchor_popup() function.
* Added support (auto-detection) for HTTP/1.1 response code 303 in redirect().
* Changed redirect() to choose the refresh method only on IIS servers, instead of all servers on
Windows (when auto is used).
* Changed anchor(), anchor_popup(), and redirect() to support protocol-relative URLs
(e.g. //ellislab.com/codeigniter).
– HTML Helper changes include:
* Added more doctypes.
* Changed application and environment config files to be loaded in a cascade-like manner.
* The doctypes array is now cached and loaded only once.
– Inflector Helper changes include:
* Changed humanize() to allow passing an input separator as its second parameter.
* Refactored plural() and singular() to avoid double pluralization and support more words.
– Download Helper changes include:
* Added an optional third parameter to force_download() that enables/disables sending the actual
file MIME type in the Content-Type header (disabled by default).
* Added a work-around in force_download() for a bug Android <= 2.1, where the filename extension needs to be in uppercase.
* Added support for reading from an existing file path by passing NULL as the second parameter to
force_download() (useful for large files and/or safely transmitting binary data).
– Form Helper changes include:
* form_dropdown() will now also take an array for unity with other form helpers.
* form_prep()‘s second argument now only accepts a boolean value, which determines whether the
value is escaped for a <textarea> or a regular <input> element.
– Security Helper changes include:
* do_hash() now uses PHP’s native hash() function (supporting more algorithms) and is deprecated.
* strip_image_tags() is now an alias for the same method in the Security Library.
– Smiley Helper changes include:
* Removed previously deprecated function js_insert_smiley().
* Changed application and environment config files to be loaded in a cascade-like manner.
* The smileys array is now cached and loaded only once.
– File Helper changes include:
274
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
* set_realpath() can now also handle file paths as opposed to just directories.
* Added an optional paramater to delete_files() to enable it to skip deleting files such as .htaccess and index.html.
* Deprecated function read_file() - it’s just an alias for PHP’s native file_get_contents().
– String Helper changes include:
* Deprecated function repeater() - it’s just an alias for PHP’s native str_repeat().
* Deprecated function trim_slashes() - it’s just an alias for PHP’s native trim() (with a slash
as its second argument).
* Deprecated randomization type options unique and encrypt for funcion random_string() (they
are only aliases for md5 and sha1 respectively).
– CAPTCHA Helper changes include:
* Added word_length and pool options to allow customization of the generated word.
* Added colors configuration to allow customization for the background, border, text and grid colors.
* Added filename to the returned array elements.
– Directory Helper directory_map() will now append DIRECTORY_SEPARATOR to directory names
in the returned array.
– Array Helper element() and elements() now return NULL instead of FALSE when the required
elements don’t exist.
– Language Helper lang() now accepts an optional list of additional HTML attributes.
– Deprecated the Email Helper as its valid_email(), send_email() functions are now only aliases
for PHP native functions filter_var() and mail() respectively.
• Database
– Added dsn configuration setting for drivers that support DSN strings (PDO, PostgreSQL, Oracle, ODBC,
CUBRID).
– Added schema configuration setting (defaults to public) for drivers that might need it (currently used by
PostgreSQL and ODBC).
– Added subdrivers support (currently only used by PDO).
– Added an optional database name parameter to db_select().
– Removed protect_identifiers() and renamed internal method _protect_identifiers()
to it instead - it was just an alias.
– Renamed internal method _escape_identifiers() to escape_identifiers().
– Updated escape_identifiers() to accept an array of fields as well as strings.
– MySQL and MySQLi drivers now require at least MySQL version 5.1.
– db_set_charset() now only requires one parameter (collation was only needed due to legacy support
for MySQL versions prior to 5.1).
– db_select() will now always (if required by the driver) be called by db_connect() /
db_pconnect() instead of only when initializing.
– Replaced the _error_message() and _error_number() methods with error(), which returns
an array containing the last database error code and message.
10.5. Change Log
275
CodeIgniter Documentation, 3.0-dev
– Improved version() implementation so that drivers that have a native function to get the version number
don’t have to be defined in the core DB_driver class.
– Added capability for packages to hold config/database.php config files.
– Added MySQL client compression support.
– Added encrypted connections support (for mysql, sqlsrv and PDO with sqlsrv).
– Removed Loader Class from Database error tracing to better find the likely culprit.
– Added support for SQLite3 database driver.
– Added Interbase/Firebird database support via the ibase driver.
– Added ODBC support for create_database(), drop_database() and drop_table() in
Database Forge.
– Query Builder changes include:
* Renamed the Active Record class to Query Builder to remove confusion with the Active Record
design pattern.
* Added the ability to insert objects with insert_batch().
* Added new methods that return the SQL string of queries without executing them:
get_compiled_select(), get_compiled_insert(), get_compiled_update(),
get_compiled_delete().
* Added an optional parameter that allows to disable escaping (useful for custom fields) for
methods join(), order_by(), where_in(), or_where_in(), where_not_in(),
or_where_not_in(), insert(), insert_batch().
* Added support for join() with multiple conditions.
* Added support for USING in join().
* Added seed values support for random ordering with order_by(seed, ’RANDOM’).
* Changed limit() to ignore NULL values instead of always casting to integer.
* Changed offset() to ignore empty values instead of always casting to integer.
* Methods insert_batch() and update_batch() now return an integer representing the number of rows affected by them.
– Database Results changes include:
* Added a constructor to the DB_result class and moved all driver-specific properties and logic out
of the base DB_driver class to allow better abstraction.
* Added method unbuffered_row() for fetching a row without prefetching the whole result (consume less memory).
* Renamed former method _data_seek() to data_seek() and made it public.
– Improved support for the MySQLi driver, including:
* OOP style of the PHP extension is now used, instead of the procedural aliases.
* Server version checking is now done via mysqli::$server_info instead of running an SQL
query.
* Added persistent connections support for PHP >= 5.3.
* Added support for backup() in Database Utilities.
276
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
* Changed methods trans_begin(), trans_commit() and trans_rollback() to use the
PHP API instead of sending queries.
– Improved support of the PDO driver, including:
* Added support for create_database(), drop_database() and drop_table() in
Database Forge.
* Added support for list_fields() in Database Results.
* Subdrivers are now isolated from each other instead of being in one large class.
– Improved support of the PostgreSQL driver, including:
* pg_version() is now used to get the database version number, when possible.
* Added db_set_charset() support.
* Added support for optimize_table() in Database Utilities (rebuilds table indexes).
* Added boolean data type support in escape().
* Added update_batch() support.
* Removed limit() and order_by() support for UPDATE and DELETE queries as PostgreSQL
does not support those features.
* Added a work-around for dead persistent connections to be re-created after a database restart.
* Changed db_connect() to include the (new) schema value into Postgre’s search_path session
variable.
* pg_escape_literal() is now used for escaping strings, if available.
– Improved support of the CUBRID driver, including:
* Added DSN string support.
* Added persistent connections support.
* Improved list_databases() in Database Utility (until now only the currently used database was
returned).
– Improved support of the MSSQL and SQLSRV drivers, including:
* Added random ordering support.
* Added support for optimize_table() in Database Utility.
* Added escaping with QUOTE_IDENTIFIER setting detection.
* Added port handling support for UNIX-based systems (MSSQL driver).
* Added OFFSET support for SQL Server 2005 and above.
* Added db_set_charset() support (MSSQL driver).
– Improved support of the Oracle (OCI8) driver, including:
* Added DSN string support (Easy Connect and TNS).
* Added support for drop_table() in Database Forge.
* Added support for list_databases() in Database Utilities.
* Generally improved for speed and cleaned up all of its components.
* num_rows() is now only called explicitly by the developer and no longer re-executes statements.
– Improved support of the SQLite driver, including:
10.5. Change Log
277
CodeIgniter Documentation, 3.0-dev
* Added support for replace() in Query Builder.
* Added support for drop_table() in Database Forge.
– Database Forge changes include:
* Added an optional second parameter to drop_table() that allows adding the IF EXISTS condition, which is no longer the default.
* Added support for passing a custom database object to the loader.
* Deprecated add_column()‘s third method. AFTER clause should now be added to the field definition array instead.
* Added support for usage of the FIRST clause in add_column() for MySQL and CUBRID.
* Overall improved support for all of the drivers.
– Database Utility changes include:
* Added support for passing a custom database object to the loader.
* Modified the class to no longer extend Database Forge, which has been a deprecated behavior for
awhile.
* Overall improved support for all of the drivers.
* Added foreign_key_checks option to MySQL/MySQLi backup, allowing statement to disable/reenable foreign key checks to be inserted into the backup output.
• Libraries
– Session Library changes include:
* Library changed to Driver with classic Cookie driver as default.
* Added Native PHP Session driver to work with $_SESSION.
* Custom drivers can be added anywhere in package paths and be loaded with the library.
* Drivers interchangeable on the fly.
* New tempdata feature allows setting user data items with an expiration time.
* Added default $config[’sess_driver’] and $config[’sess_valid_drivers’]
items to config.php file.
* Cookie driver now respects php.ini’s session.gc_probability and session.gc_divisor settings.
* Cookie driver now uses HMAC authentication instead of the simple md5 checksum.
* The Cookie driver now also checks authentication on encrypted session data.
* Changed the Cookie driver to select only one row when using database sessions.
* Cookie driver now only writes to database at end of request when using database.
* Cookie driver now uses PHP functions for faster array manipulation when using database.
* Added all_flashdata() method to session class. Returns an associative array of only flashdata.
* Added has_userdata() method to verify existence of userdata item.
* Added tempdata(), set_tempdata(), and unset_tempdata() methods for manipulating
tempdata.
* keep_flashdata() now accepts an array of keys.
* Added debug level log messages for key events in the session validation process.
278
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
– File Uploading Library changes include:
* Added max_filename_increment config setting.
* Added an index parameter to the data() method.
* Added the min_width and min_height options for images.
* Removed method clean_file_name() and its usage in favor of Security Library‘s
sanitize_filename().
* Added file_ext_tolower config setting.
* Added mod_mime_fix option to disable suffixing multiple file extensions with an underscore.
– Cart library changes include:
* insert() now auto-increments quantity for an item when inserted twice instead of resetting it, this
is the default behaviour of large e-commerce sites.
* Product Name strictness can be disabled by switching the $product_name_safe property to
FALSE.
* Added method remove() to remove a cart item, updating with quantity of 0 seemed like a hack but
has remained to retain compatibility.
* Added method get_item() to enable retrieving data for a single cart item.
* Added unicode support for product names.
– Image Manipulation library changes include:
* The initialize() method now only sets existing class properties.
* Added support for 3-length hex color values for wm_font_color and wm_shadow_color properties, as
well as validation for them.
* Class properties wm_font_color, wm_shadow_color and wm_use_drop_shadow are now protected, to
avoid breaking the text_watermark() method if they are set manually after initialization.
* If property maintain_ratio is set to TRUE, image_reproportion() now doesn’t need both width
and height to be specified.
* Property maintain_ratio is now taken into account when resizing images using ImageMagick library.
* Added support for maintaining transparency for PNG images in method text_watermark().
– Form Validation library changes include:
* Added method error_array() to return all error messages as an array.
* Added method set_data() to set an alternative data array to be validated instead of the default
$_POST.
* Added method reset_validation() which resets internal validation variables in case of multiple validation routines.
* Added support for setting error delimiters in the config file via $config[’error_prefix’] and
$config[’error_suffix’].
* Internal method _execute() now considers input data to be invalid if a specified rule is not found.
* Removed method is_numeric() as it exists as a native PHP function and _execute() will find
and use that (the is_numeric rule itself is deprecated since 1.6.1).
* Native PHP functions used as rules can now accept an additional parameter, other than the data itself.
* Updated method set_rules() to accept an array of rules as well as a string.
10.5. Change Log
279
CodeIgniter Documentation, 3.0-dev
* Fields that have empty rules set no longer run through validation (and therefore are not considered
erroneous).
* Added rule differs to check if the value of a field differs from the value of another field.
* Added rule valid_url.
* Added support for named parameters in error messages.
* Language line keys must now be prefixed with form_validation_.
* Added rule alpha_numeric_spaces.
– Caching Library changes include:
* Added Wincache driver.
* Added Redis driver.
* Added a key_prefix option for cache IDs.
* Updated driver is_supported() methods to log at the “debug” level.
– Email library changes include:
* Added custom filename to Email::attach() as $this->email->attach($filename,
$disposition, $newname).
* Added possibility to send attachment as buffer string in Email::attach()
$this->email->attach($buffer, $disposition, $newname, $mime).
as
* Added dsn (delivery status notification) option.
* Renamed method _set_header() to set_header() and made it public to enable adding custom headers
in the Email Library.
* Successfully sent emails will automatically clear the parameters.
* Added a return_path parameter to the from() method.
the
second
parameter
(character
* Removed
_prep_quoted_printable() as it is never used.
limit)
from
internal
method
method
_prep_quoted_printable()
will
now
utilize
the
native
* Internal
quoted_printable_encode(), imap_8bit() functions (if available) when CRLF is
set to “rn”.
* Default charset now relies on the global $config[’charset’] setting.
* Removed unused protected method _get_ip() (Input Library‘s ip_address() should be used
anyway).
* Internal method _prep_q_encoding() now utilizes PHP’s mbstring and iconv extensions (when
available) and no longer has a second ($from) argument.
* Added an optional parameter to print_debugger() to allow specifying which parts of the message should be printed (‘headers’, ‘subject’, ‘body’).
* Added SMTP keepalive option to avoid opening the connection for each Email::send(). Accessible as $smtp_keepalive.
* Public method set_header() now filters the input by removing all “\r” and “\n” characters.
– Pagination Library changes include:
* Added support for the anchor “rel” attribute.
* Added support for setting custom attributes.
280
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
* Deprecated usage of the “anchor_class” setting (use the new “attributes” setting instead).
* Added $config[’reuse_query_string’] to allow automatic repopulation of query string arguments, combined with normal URI segments.
* Removed the default &nbsp; from a number of the configuration variables.
* Added the ability to use a proxy with the XML-RPC Library.
– Encryption Library changes include:
* Added support for hashing algorithms other than SHA1 and MD5.
* Removed previously deprecated sha1() method.
– Profiler Library changes include:
* Database object names are now being displayed.
* The sum of all queries running times in seconds is now being displayed.
* Added support for displaying the HTTP DNT (“Do Not Track”) header.
* Added support for displaying $_FILES.
– Migration Library changes include:
* Added support for timestamp-based migrations (enabled by default).
* Added $config[’migration_type’] to allow switching between sequential and timestamp
migrations.
– User Agent Library will now check if robots are pretending to be mobile clients (helps with e.g. Google
indexing mobile website versions).
– Added support for setting Table class defaults in a config file.
• Core
– URI Library changes include:
* Changed private methods to protected so that MY_URI can override them.
* Renamed internal method _parse_cli_args() to _parse_argv().
* Renamed internal method _detect_uri() to _parse_request_uri().
* Changed _parse_request_uri() to accept absolute URIs for compatibility with HTTP/1.1 as
per RFC2616 <http://www.ietf.org/rfc/rfc2616.txt>.
* Added protected method _parse_query_string() to URI paths in the the QUERY_STRING
value, like _parse_request_uri() does.
* Changed _fetch_uri_string() to try the PATH_INFO variable first when auto-detecting.
– Loader Library changes include:
* Added method get_vars()
$this->load->vars().
to
the
Loader
to
retrieve
all
variables
loaded
with
* _ci_autoloader() is now a protected method.
* Added autoloading of drivers with $autoload[’drivers’].
* $config[’rewrite_short_tags’] now has no effect when using PHP 5.4 as <?= will always
be available.
* Changed method config() to return whatever CI_Config::load() returns instead of always
being void.
10.5. Change Log
281
CodeIgniter Documentation, 3.0-dev
* Added support for model aliasing on autoload.
* Changed method is_loaded() to ask for the (case sensitive) library name instead of its instance
name.
* Removed $_base_classes property and unified all class data in $_ci_classes instead.
* Added method clear_vars() to allow clearing the cached variables for views.
– Input Library changes include:
* Added method() to retrieve $_SERVER[’REQUEST_METHOD’].
* Added support for arrays and network addresses (e.g. 192.168.1.1/24) for use with the proxy_ips
setting.
* Added method input_stream() to aid in using php://input stream data such as one passed via
PUT, DELETE and PATCH requests.
* Changed method valid_ip() to use PHP’s native filter_var() function.
* Changed internal method _sanitize_globals() to skip enforcing reversal of register_globals
in PHP 5.4+, where this functionality no longer exists.
* Changed methods get(), post(), get_post(), cookie(), server(), user_agent() to
return NULL instead of FALSE when no value is found.
* Added method post_get() and changed get_post() to search in GET data first. Both methods’
names now properly match their GET/POST data search priorities.
* Changed method _fetch_from_array() to parse array notation in field name.
* Added an option for _clean_input_keys() to return FALSE instead of terminating the whole
script.
* Deprecated the is_cli_request() method, it is now an alias for the new is_cli() common
function.
– Common functions changes include:
* Added function get_mimes() to return the application/config/mimes.php array.
* Added support for HTTP code 303 (“See Other”) in set_status_header().
* Removed redundant conditional to determine HTTP server protocol in set_status_header().
* Changed _exception_handler() to respect php.ini display_errors setting.
* Added function is_https() to check if a secure connection is used.
* Added function is_cli() to replace the CI_Input::is_cli_request() method.
* Added function function_usable() to check if a function exists and is not disabled by Suhosin
<http://www.hardened-php.net/suhosin/>.
* Removed the third ($php_error) from function log_message().
– Output Library changes include:
* Added a second argument to method set_content_type() that allows setting the document
charset as well.
* Added methods get_content_type() and get_header().
* Added method delete_cache().
– Config Library changes include:
282
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
* Changed site_url() method to accept an array as well.
* Removed internal method _assign_to_config() and moved its implementation to
CodeIgniter.php instead.
* item() now returns NULL instead of FALSE when the required config item doesn’t exist.
* Added an optional second parameter to both base_url() and site_url() that allows enforcing
of a protocol different than the one in the base_url configuration setting.
– Security Library changes include:
* Added method strip_image_tags().
* Added $config[’csrf_regeneration’], which makes token regeneration optional.
* Added $config[’csrf_exclude_uris’], which allows you list URIs which will not have the
CSRF validation methods run.
* Modified method sanitize_filename() to read a public $filename_bad_chars property
for getting the invalid characters list.
– URI Routing changes include:
* Added possibility to route requests using HTTP verbs.
* Added possibility to route requests using callbacks.
* Added a new reserved route (translate_uri_dashes) to allow usage of dashes in the controller and
method URI segments.
* Deprecated methods fetch_directory(), fetch_class() and fetch_method() in favor
of their respective public properties.
– Language Library changes include:
* Changed method load() to filter the language name with ctype_digit().
* Added an optional second parameter to method line() to disable error login for line keys that were
not found.
* Language files are now loaded in a cascading style with the one in system/ always loaded and overriden afterwards, if another one is found.
– Removed CI_CORE boolean constant from CodeIgniter.php (no longer Reactor and Core versions).
– Log Library will now try to create the log_path directory if it doesn’t exist.
– Added support for HTTP-Only cookies with new config option cookie_httponly (default FALSE).
– Renamed method _call_hook() to call_hook() in the Hooks Library.
– $config[’time_reference’] now supports all timezone strings supported by PHP.
– Fatal PHP errors are now also passed to _exception_handler(), so they can be logged.
Bug fixes for 3.0
• Fixed a bug where unlink() raised an error if cache file did not exist when you try to delete it.
• Fixed a bug (#181) where a mis-spelling was in the form validation language file.
• Fixed a bug (#159, #163) - Query Builder nested transactions didn’t work properly due to _trans_depth not
being incremented.
• Fixed a bug (#737, #75) - Pagination anchor class was not set properly when using initialize method.
10.5. Change Log
283
CodeIgniter Documentation, 3.0-dev
• Fixed a bug (#419) - auto_link() didn’t recognize URLs that come after a word boundary.
• Fixed a bug (#724) - Form Validation Library rule is_unique didn’t check if a database connection exists.
• Fixed a bug (#647) - Zip Library internal method _get_mod_time() didn’t suppress possible “stat failed”
errors generated by filemtime().
• Fixed a bug (#157, #174) - Image Manipulation Library method clear() didn’t completely clear properties.
• Fixed a bug where Database Forge method create_table() with PostgreSQL database could lead to fetching the whole table.
• Fixed a bug (#795) - Form Helper form_open() didn’t add the default form method and accept-charset when
an empty array is passed to it.
• Fixed a bug (#797) - timespan() was using incorrect seconds for year and month.
• Fixed a bug in CI_Cart::contents() where if called without a TRUE (or equal) parameter, it would fail due to a
typo.
• Fixed a bug (#696) - make oci_execute() calls inside num_rows() non-committing, since they are only there to
reset which row is next in line for oci_fetch calls and thus don’t need to be committed.
• Fixed a bug (#406) - SQLSRV DB driver not returning resource on db_pconnect().
• Fixed a bug in CI_Image_lib::gd_loaded() where it was possible for the script execution to end or a PHP
E_WARNING message to be emitted.
• Fixed a bug in the Pagination library where when use_page_numbers=TRUE previous link and page 1 link did
not have the same url.
• Fixed a bug (#561) - Errors in XML-RPC Library were not properly escaped.
• Fixed a bug (#904) - CI_Loader::initialize() caused a PHP Fatal error to be triggered if error level
E_STRICT is used.
• Fixed a hosting edge case where an empty $_SERVER[’HTTPS’] variable would evaluate to ‘on’.
• Fixed a bug (#154) - CI_Session::sess_update() caused the session to be destroyed on pages where
multiple AJAX requests were executed at once.
• Fixed a possible bug in CI_Input::is_ajax_request() where some clients might not send the XRequested-With HTTP header value exactly as ‘XmlHttpRequest’.
• Fixed a bug (#1039) - MySQL’s _backup() method failed due to a table name not being escaped.
• Fixed a bug (#1070) - CI_DB_driver::initialize() didn’t set a character set if a database is not selected.
• Fixed a bug (#177) - CI_Form_validation::set_value() didn’t set the default value if POST data is
NULL.
• Fixed a bug (#68, #414) - Oracle’s escape_str() didn’t properly escape LIKE wild characters.
• Fixed a bug (#81) - ODBC’s list_fields() and field_data() methods skipped the first column due to odbc_field_*()
functions’ index starting at 1 instead of 0.
• Fixed a bug (#129) - ODBC’s num_rows() returned -1 in some cases, due to not all subdrivers supporting the
odbc_num_rows() function.
• Fixed a bug (#153) - E_NOTICE being generated by getimagesize() in the File Uploading Library.
• Fixed a bug (#611) - SQLSRV’s error handling methods used to issue warnings when there’s no actual error.
• Fixed a bug (#1036) - is_write_type() method in the Database Library didn’t return TRUE for RENAME
queries.
• Fixed a bug in PDO’s _version() method where it used to return the client version as opposed to the server one.
284
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Fixed a bug in PDO’s insert_id() method where it could’ve failed if it’s used with Postgre versions prior to 8.1.
• Fixed a bug in CUBRID’s affected_rows() method where a connection resource was passed to
cubrid_affected_rows() instead of a result.
• Fixed a bug (#638) - db_set_charset() ignored its arguments and always used the configured charset instead.
• Fixed a bug (#413) - Oracle’s error handling methods used to only return connection-related errors.
• Fixed a bug (#1101) - MySQL/MySQLi result method field_data() was implemented as if it was handling a
DESCRIBE result instead of the actual result set.
• Fixed a bug in Oracle’s Database Forge Class method _create_table() where it failed with AUTO_INCREMENT
as it’s not supported.
• Fixed a bug (#1080) - When using the SMTP protocol, the Email Library send() method was returning TRUE
even if the connection/authentication against the server failed.
• Fixed a bug (#306) - ODBC’s insert_id() method was calling non-existent function odbc_insert_id(), which
resulted in a fatal error.
• Fixed a bug in Oracle’s DB_result class where the cursor id passed to it was always NULL.
• Fixed a bug (#64) - Regular expression in DB_query_builder.php failed to handle queries containing SQL
bracket delimiters in the join condition.
• Fixed a bug in the Session Library where a PHP E_NOTICE error was triggered by _unserialize() due to results
from databases such as MSSQL and Oracle being space-padded on the right.
• Fixed a bug (#501) - set_rules() to check if the request method is not ‘POST’ before aborting, instead of depending on count($_POST) in the Form Validation Library.
• Fixed a bug (#136) - PostgreSQL, MySQL and MySQLi’s escape_str() method didn’t properly escape LIKE
wild characters.
• Fixed a bug in the library loader where some PHP versions wouldn’t execute the class constructor.
• Fixed a bug (#88) - An unexisting property was used for configuration of the Memcache cache driver.
• Fixed a bug (#14) - create_database() method in the Database Forge Library didn’t utilize the configured
database character set.
• Fixed a bug (#23, #1238) - delete_all() in the Database Caching Library <database/caching> used to delete
.htaccess and index.html files, which is a potential security risk.
• Fixed a bug in Trackback Library method validate_url() where it didn’t actually do anything, due to input not
being passed by reference.
• Fixed a bug (#11, #183, #863) - CI_Form_validation::_execute() silently continued to the next rule, if a rule
method/function is not found.
• Fixed a bug (#122) - routed URI string was being reported incorrectly in sub-directories.
• Fixed a bug (#1242) - read_dir() in the Zip Library wasn’t compatible with Windows.
• Fixed a bug (#306) - ODBC driver didn’t have an _insert_batch() method, which resulted in fatal error being
triggered when insert_batch() is used with it.
• Fixed a bug in MSSQL and SQLSrv’s _truncate() where the TABLE keyword was missing.
• Fixed a bug in PDO’s trans_commit() method where it failed due to an erroneous property name.
• Fixed a bug (#798) - update() used to ignore LIKE conditions that were set with like().
• Fixed a bug in Oracle’s and MSSQL’s delete() methods where an erroneous SQL statement was generated when
used with limit().
10.5. Change Log
285
CodeIgniter Documentation, 3.0-dev
• Fixed a bug in SQLSRV’s delete() method where like() and limit() conditions were ignored.
• Fixed a bug (#1265) - Database connections were always closed, regardless of the ‘pconnect’ option value.
• Fixed a bug (#128) - Language Library did not correctly keep track of loaded language files.
• Fixed a bug (#1242) - Added Windows path compatibility to function read_dir of ZIP library.
• Fixed a bug (#1349) - get_extension() in the File Uploading Library returned the original filename when it didn’t
have an actual extension.
• Fixed a bug (#1273) - E_NOTICE being generated by Query Builder‘s set_update_batch() method.
• Fixed a bug (#44, #110) - Upload library‘s clean_file_name() method didn’t clear ‘!’ and ‘#’ characters.
• Fixed a bug (#121) - CI_DB_result::row() returned an array when there’s no actual result to be returned.
• Fixed a bug (#319) - SQLSRV’s affected_rows() method failed due to a scrollable cursor being created for
write-type queries.
• Fixed a bug (#356) - PostgreSQL driver didn’t have an _update_batch() method, which resulted in fatal error
being triggered when update_batch() is used with it.
• Fixed a bug (#784, #862) - Database Forge method create_table() failed on SQLSRV/MSSQL when
used with ‘IF NOT EXISTS’.
• Fixed a bug (#1419) - libraries/Driver.php had a static variable that was causing an error.
• Fixed a bug (#1411) - the Email library used its own short list of MIMEs instead the one from config/mimes.php.
• Fixed a bug where the magic_quotes_runtime setting wasn’t turned off for PHP 5.3 (where it is indeed deprecated, but not non-existent).
• Fixed a bug (#666) - Output library‘s set_content_type() method didn’t set the document charset.
• Fixed a bug (#784, #861) - Database Forge method create_table() used to accept constraints for
MSSQL/SQLSRV integer-type columns.
• Fixed a bug (#706) - SQLSRV/MSSSQL didn’t escape field names.
• Fixed a bug (#1452) - protect_identifiers() didn’t properly detect identifiers with spaces in their
names.
• Fixed a bug where protect_identifiers() ignored its extra arguments when the value passed to it is an
array.
• Fixed a bug where _has_operator() didn’t detect BETWEEN.
• Fixed a bug in Query Builder‘s join() method where it failed with identifiers containing dashes.
• Fixed a bug (#1264) - Database Forge and Database Utilities didn’t update/reset the databases and tables list
cache when a table or a database is created, dropped or renamed.
• Fixed a bug (#7) - Query Builder‘s join() method only escaped one set of conditions.
• Fixed a bug (#1321) - Core Exceptions class couldn’t find the errors/ folder in some cases.
• Fixed a bug (#1202) - Encryption Library encode_from_legacy() didn’t set back the encrypt mode on failure.
• Fixed a bug (#145) - compile_binds() failed when the bind marker was present in a literal string within the query.
• Fixed a bug in protect_identifiers() where if passed along with the field names, operators got escaped as well.
• Fixed a bug (#10) - URI Library internal method _detect_uri() failed with paths containing a colon.
• Fixed a bug (#1387) - Query Builder‘s from() method didn’t escape table aliases.
• Fixed a bug (#520) - Date Helper function nice_date() failed when the optional second parameter is not passed.
286
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Fixed a bug (#167) - $config[’permitted_uri_chars’] didn’t affect URL-encoded characters.
• Fixed a bug (#318) - Profiling setting query_toggle_count was not settable as described in the manual.
• Fixed a bug (#938) - Config Library method site_url() added a question mark to the URL string when
query strings are enabled even if it already existed.
• Fixed a bug (#999) - Config Library method site_url() always appended $config[’url_suffix’]
to the end of the URL string, regardless of whether a query string exists in it.
• Fixed a bug where URL Helper function anchor_popup() ignored the attributes argument if it is not an
array.
• Fixed a bug (#1328) - Form Validation Library didn’t properly check the type of the form fields before processing
them.
• Fixed a bug (#79) - Form Validation Library didn’t properly validate array fields that use associative keys or
have custom indexes.
• Fixed a bug (#427) - Form Validation Library method strip_image_tags() was an alias to a non-existent
method.
• Fixed a bug (#1545) - Query Builder method limit() wasn’t executed properly under Oracle.
• Fixed a bug (#1551) - Date Helper function standard_date() didn’t properly format W3C and ATOM
standard dates.
• Fixed a bug in Query Builder method join() where literal values were escaped as if they were fields.
• Fixed a bug (#135) - PHP Error logging was impossible without the errors being displayed.
• Fixed a bug (#1613) - Form Helper functions form_multiselect(), form_dropdown() didn’t properly
handle empty array option groups.
• Fixed a bug (#1605) - Pagination Library produced incorrect previous and next link values.
• Fixed a bug in SQLSRV’s affected_rows() method where an erroneous function name was used.
• Fixed a bug (#1000) - Change syntax of $view_file to $_ci_view_file to prevent being overwritten by
application.
• Fixed a bug (#1757) - Directory Helper function directory_map() was skipping files and directories named
0.
• Fixed a bug (#1789) - Database Library method escape_str() escaped quote characters in LIKE conditions
twice under MySQL.
• Fixed a bug (#395) - Unit Testing Library method result() didn’t properly check array result columns when
called from report().
• Fixed a bug (#1692) - Database Library method display_error() didn’t properly trace the possible error
source on Windows systems.
• Fixed a bug (#1745) - is_write_type() method in the Database Library didn’t return TRUE for LOAD
queries.
• Fixed a bug (#1765) - Database Library didn’t properly detect connection errors for MySQLi.
• Fixed a bug (#1257) - Query Builder used to (unnecessarily) group FROM clause contents, which breaks certain
queries and is invalid for some databases.
• Fixed a bug (#1709) - Email headers were broken when using long email subjects and rn as CRLF.
• Fixed a bug where MB_ENABLED was only declared if UTF8_ENABLED was set to TRUE.
• Fixed a bug where the Session Library accepted cookies with last_activity values being in the future.
10.5. Change Log
287
CodeIgniter Documentation, 3.0-dev
• Fixed a bug (#1897) - Email Library triggered PHP E_WARNING errors when mail protocol used and to() is
never called.
• Fixed a bug (#1409) - Email Library didn’t properly handle multibyte characters when applying Q-encoding to
headers.
• Fixed a bug where Email Library didn’t honor its wordwrap setting while handling alternative messages.
• Fixed a bug (#1476, #1909) - Pagination Library didn’t take into account actual routing when determining the
current page.
• Fixed a bug (#1766) - Query Builder didn’t always take into account the dbprefix setting.
• Fixed a bug (#779) - URI Class didn’t always trim slashes from the uri_string as shown in the documentation.
• Fixed a bug (#134) - Database Caching method delete_cache() didn’t work in some cases due to cachedir
not being initialized properly.
• Fixed a bug (#191) - Loader Library ignored attempts for (re)loading databases to get_instance()->db
even when the old database connection is dead.
• Fixed a bug (#1255) - User Agent
$_SERVER[’HTTP_REFERER’] exists.
Library
method
is_referral()
only
checked
if
• Fixed a bug (#1146) - Download Helper function force_download() incorrectly sent Cache-Control directives pre-check and post-check to Internet Explorer.
• Fixed a bug (#1811) - URI Library didn’t properly cache segments for uri_to_assoc() and
ruri_to_assoc().
• Fixed a bug (#1506) - Form Helpers set empty name attributes.
• Fixed a bug (#59) - Query Builder method count_all_results() ignored the DISTINCT clause.
• Fixed a bug (#1624) - Form Validation Library rule matches didn’t property handle array field names.
• Fixed a bug (#1630) - Form Helper function set_value() didn’t escape HTML entities.
• Fixed a bug (#142) - Form Helper function form_dropdown() didn’t escape HTML entities in option values.
• Fixed a bug (#50) - Session Library unnecessarily stripped slashed from serialized data, making it impossible to
read objects in a namespace.
• Fixed a bug (#658) - Routing wildcard :any didn’t work as advertised and matched multiple URI segments
instead of all characters within a single segment.
• Fixed a bug (#1938) - Email Library removed multiple spaces inside a pre-formatted plain text message.
• Fixed a bug (#388, #705) - URI Library didn’t apply URL-decoding to URI segments that it got from REQUEST_URI and/or QUERY_STRING.
• Fixed a bug (#122) - URI Library method ruri_string() didn’t include a directory if one is used.
• Fixed a bug - Routing Library didn’t properly handle default_controller in a subdirectory when a method is also
specified.
• Fixed a bug (#953) - post_controller_constructor hook wasn’t called with a 404_override.
• Fixed a bug (#1220) - Profiler Library didn’t display information for database objects that are instantiated inside
models.
• Fixed a bug (#1978) - Directory Helper function directory_map()‘s return array didn’t make a distinction
between directories and file indexes when a directory with a numeric name is present.
• Fixed a bug (#777) - Loader Library didn’t look for helper extensions in added package paths.
• Fixed a bug (#18) - APC Cache driver didn’t (un)serialize data, resulting in failure to store objects.
288
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Fixed a bug (#188) - Unit Testing Library filled up logs with error messages for non-existing language keys.
• Fixed a bug (#113) - Form Validation Library didn’t properly handle empty fields that were specified as an array.
• Fixed a bug (#2061) - Routing Class didn’t properly sanitize directory, controller and function triggers with
enable_query_strings set to TRUE.
• Fixed a bug - SQLSRV didn’t support escape_like_str() or escaping an array of values.
• Fixed a bug - Database Results method list_fields() didn’t reset its field pointer for the mysql, mysqli
and mssql drivers.
• Fixed a bug (#73) - Security Library method sanitize_filename() could be tricked by an XSS attack.
• Fixed a bug (#2211) - Migration Library extensions couldn’t execute CI_Migration::__construct().
• Fixed a bug (#2255) - Email Library didn’t apply smtp_timeout to socket reads and writes.
• Fixed a bug (#2239) - Email Library improperly handled the Subject when used with bcc_batch_mode
resulting in E_WARNING messages and an empty Subject.
• Fixed a bug (#2234) - Query Builder didn’t reset JOIN cache for write-type queries.
• Fixed a bug (#2298) - Database Results method next_row() kept returning the last row, allowing for infinite
loops.
• Fixed a bug (#2236, #2639) - Form Helper functions set_value(), set_select(), set_radio(),
set_checkbox() didn’t parse array notation for keys if the rule was not present in the Form Validation
Library.
• Fixed a bug (#2353) - Query Builder erroneously prefixed literal strings with dbprefix.
• Fixed a bug (#78) - Cart Library didn’t allow non-English letters in product names.
• Fixed a bug (#77) - Database Class didn’t properly handle the transaction “test mode” flag.
• Fixed a bug (#2380) - URI Routing method fetch_method() returned ‘index’ if the requested method name
matches its controller name.
• Fixed a bug (#2388) - Email Library used to ignore attachment errors, resulting in broken emails being sent.
• Fixed a bug (#2498) - Form Validation Library rule valid_base64 only checked characters instead of actual
validity.
• Fixed a bug (#2425) - OCI8 database driver’s method stored_procedure() didn’t log an error unless
db_debug was set to TRUE.
• Fixed a bug (#2490) - Database Class method query() returning boolean instead of a result object when the
PostgreSQL-specific RETURNING clause is used.
• Fixed a bug (#249) - Cache Library didn’t properly handle Memcache(d) configurations with missing options.
• Fixed a bug (#180) - config_item() didn’t take into account run-time configuration changes.
• Fixed a bug (#2551) - Loader Library method library() didn’t properly check if a class that is being loaded
already exists.
• Fixed a bug (#2560) - Form Helper function form_open() set the ‘method=”post”’ attribute only if the passed
attributes equaled an empty string.
• Fixed a bug (#2585) - Query Builder methods min(), max(), avg(), sum() didn’t escape field names.
• Fixed an edge case (#2583) in the Email Library where Suhosin <http://www.hardened-php.net/suhosin/>
blocked messages sent via mail() due to trailing newspaces in headers.
• Fixed a bug (#2590) - log_message() didn’t actually cache the CI_Log class instance.
10.5. Change Log
289
CodeIgniter Documentation, 3.0-dev
• Fixed a bug (#2609) - get_config() optional argument was only effective on first function call. Also, it can
now add items, in addition to updating existing items.
• Fixed a bug in the ‘postgre’ database driver where the connection ID wasn’t passed to
pg_escape_string().
• Fixed a bug (#33) - Script execution was terminated when an invalid cookie key was encountered.
• Fixed a bug (#2681) - CI_Security::entity_decode() used the PREG_REPLACE_EVAL flag, which
is deprecated since PHP 5.5.
• Fixed a bug (#2691) - nested transactions could end in a deadlock when an error is encountered with db_debug
set to TRUE.
• Fixed a bug (#2515) - _exception_handler() used to send the 200 “OK” HTTP status code and didn’t
stop script exection even on fatal errors.
• Fixed a bug - Redis Caching driver didn’t handle connection failures properly.
• Fixed a bug (#2756) - Database Class executed the MySQL-specific SET SESSION sql_mode query for all
drivers when the ‘stricton’ option is set.
10.5.2 Version 2.1.4
Release Date: July 8, 2013
• General Changes
– Improved security in xss_clean().
Bug fixes for 2.1.4
• Fixed a bug (#1936) - Migration Library method latest() had a typo when retrieving language values.
• Fixed a bug (#2021) - Migration Library configuration file was mistakenly using Windows style line feeds.
• Fixed a bug (#1273) - E_NOTICE being generated by Query Builder‘s set_update_batch() method.
• Fixed a bug (#2337) - Email Library method print_debugger() didn’t apply htmlspecialchars()
to headers.
10.5.3 Version 2.1.3
Release Date: October 8, 2012
• Core
– Common function is_loaded() now returns a reference.
Bug fixes for 2.1.3
• Fixed a bug (#1543) - File-based Caching method get_metadata() used a non-existent array key to look
for the TTL value.
• Fixed a bug (#1314) - Session Library method sess_destroy() didn’t destroy the userdata array.
• Fixed a bug (#804) - Profiler library was trying to handle objects as strings in some cases, resulting in
E_WARNING messages being issued by htmlspecialchars().
290
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Fixed a bug (#1699) - Migration Library ignored the $config[’migration_path’] setting.
• Fixed a bug (#227) - Input Library allowed unconditional spoofing of HTTP clients’ IP addresses through the
HTTP_CLIENT_IP header.
• Fixed a bug (#907) - Input Library ignored HTTP_X_CLUSTER_CLIENT_IP and HTTP_X_CLIENT_IP headers when checking for proxies.
• Fixed a bug (#940) - csrf_verify() used to set the CSRF cookie while processing a POST request with no
actual POST data, which resulted in validating a request that should be considered invalid.
• Fixed a bug (#499) - Security Library where
$config[’csrf_protection’] is set tot FALSE.
a
CSRF
cookie
was
created
even
if
• Fixed a bug (#1715) - Input Library triggered csrf_verify() on CLI requests.
• Fixed a bug (#751) - Query Builder didn’t properly handle cached field escaping overrides.
• Fixed a bug (#2004) - Query Builder didn’t properly merge cached calls with non-cache ones.
10.5.4 Version 2.1.2
Release Date: June 29, 2012
• General Changes
– Improved security in xss_clean().
10.5.5 Version 2.1.1
Release Date: June 12, 2012
• General Changes
– Fixed support for docx, xlsx files in mimes.php.
• Libraries
– Further improved MIME type detection in the File Uploading Library.
– Added support for IPv6 to the Input Library.
– Added support for the IP format parameter to the Form Validation Library.
• Helpers
– url_title() performance and output improved. You can now use any string as the word delimiter, but
‘dash’ and ‘underscore’ are still supported.
Bug fixes for 2.1.1
• Fixed a bug (#697) - A wrong array key was used in the File Uploading Library to check for mime-types.
• Fixed a bug - form_open() compared $action against site_url() instead of base_url().
• Fixed a bug - CI_Upload::_file_mime_type() could’ve failed if mime_content_type() is used
for the detection and returns FALSE.
• Fixed a bug (#538) - Windows paths were ignored when using the Image Manipulation Library to create a new
file.
10.5. Change Log
291
CodeIgniter Documentation, 3.0-dev
• Fixed a bug - When database caching was enabled, $this->db->query() checked the cache before binding variables which resulted in cached queries never being found.
• Fixed a bug - CSRF cookie value was allowed to be any (non-empty) string before being written to the output,
making code injection a risk.
• Fixed a bug (#726) - PDO put a ‘dbname’ argument in its connection string regardless of the database platform
in use, which made it impossible to use SQLite.
• Fixed a bug - CI_DB_pdo_driver::num_rows() was not returning properly value with SELECT queries,
cause it was relying on PDOStatement::rowCount().
• Fixed a bug (#1059) - CI_Image_lib::clear() was not correctly clearing all necessary object properties,
namely width and height.
10.5.6 Version 2.1.0
Release Date: November 14, 2011
• General Changes
– Callback validation rules can now accept parameters like any other validation rule.
– Added html_escape() to Common functions to escape HTML output for preventing XSS.
• Helpers
– Added increment_string() to String Helper to turn “foo” into “foo-1” or “foo-1” into “foo-2”.
– Altered form helper - made action on form_open_multipart helper function call optional. Fixes (#65)
– url_title() will now trim extra dashes from beginning and end.
– Improved speed of String Helper‘s random_string() method
• Database
– Added a CUBRID driver to the Database Driver. Thanks to the CUBRID team for supplying this patch.
– Added a PDO driver to the Database Driver.
– Typecast limit and offset in the Database Driver to integers to avoid possible injection.
– Added additional option ‘none’ for the optional third argument for $this->db->like() in the Database
Driver.
– Added $this->db->insert_batch() support to the OCI8 (Oracle) driver.
– Added failover if the main connections in the config should fail
• Libraries
– Changed $this->cart->insert() in the Cart Library to return the Row ID if a single item was
inserted successfully.
– Added support to set an optional parameter in your callback rules of validation using the Form Validation
Library.
– Added a Migration library to assist with applying incremental updates to your database schema.
– Driver children can be located in any package path.
– Added max_filename_increment config setting for Upload library.
– Added is_unique to the Form Validation library.
292
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
– Added $config[’use_page_numbers’] to the Pagination library, which enables real page numbers in the
URI.
– Added TLS and SSL Encryption for SMTP.
• Core
– Changed private functions in CI_URI to protected so MY_URI can override them.
– Removed CI_CORE boolean constant from CodeIgniter.php (no longer Reactor and Core versions).
Bug fixes for 2.1.0
• Fixed #378 Robots identified as regular browsers by the User Agent class.
• If a config class was loaded first then a library with the same name is loaded, the config would be ignored.
• Fixed a bug (Reactor #19) where 1) the 404_override route was being ignored in some cases, and 2) auto-loaded
libraries were not available to the 404_override controller when a controller existed but the requested method
did not.
• Fixed a bug (Reactor #89) where MySQL export would fail if the table had hyphens or other non alphanumeric/underscore characters.
• Fixed a bug (#105) that stopped query errors from being logged unless database debugging was enabled
• Fixed a bug (#160) - Removed unneeded array copy in the file cache driver.
• Fixed a bug (#150) - field_data() now correctly returns column length.
• Fixed a bug (#8) - load_class() now looks for core classes in APPPATH first, allowing them to be replaced.
• Fixed a bug (#24) - ODBC database driver called incorrect parent in __construct().
• Fixed a bug (#85) - OCI8 (Oracle) database escape_str() function did not escape correct.
• Fixed a bug (#344) - Using schema found in Saving Session Data to a Database, system would throw error
“user_data does not have a default value” when deleting then creating a session.
• Fixed a bug (#112) - OCI8 (Oracle) driver didn’t pass the configured database character set when connecting.
• Fixed a bug (#182) - OCI8 (Oracle) driver used to re-execute the statement whenever num_rows() is called.
• Fixed a bug (#82) - WHERE clause field names in the DB update_string() method were not escaped, resulting
in failed queries in some cases.
• Fixed a bug (#89) - Fix a variable type mismatch in DB display_error() where an array is expected, but a string
could be set instead.
• Fixed a bug (#467) - Suppress warnings generated from get_magic_quotes_gpc() (deprecated in PHP 5.4)
• Fixed a bug (#484) - First time _csrf_set_hash() is called, hash is never set to the cookie (in Security.php).
• Fixed a bug (#60) - Added _file_mime_type() method to the File Uploading Library in order to fix a possible
MIME-type injection.
• Fixed a bug (#537) - Support for all wav type in browser.
• Fixed a bug (#576) - Using ini_get() function to detect if apc is enabled or not.
• Fixed invalid date time format in Date helper and XMLRPC library.
• Fixed a bug (#200) - MySQL queries would be malformed after calling db->count_all() then db->get().
10.5. Change Log
293
CodeIgniter Documentation, 3.0-dev
10.5.7 Version 2.0.3
Release Date: August 20, 2011
• Security
– An improvement was made to the MySQL and MySQLi drivers to prevent exposing a potential vector for
SQL injection on sites using multi-byte character sets in the database client connection. An incompatibility
in PHP versions < 5.2.3 and MySQL < 5.0.7 with mysql_set_charset() creates a situation where using
multi-byte character sets on these environments may potentially expose a SQL injection attack vector.
Latin-1, UTF-8, and other “low ASCII” character sets are unaffected on all environments.
If you are running or considering running a multi-byte character set for your database connection, please
pay close attention to the server environment you are deploying on to ensure you are not vulnerable.
• General Changes
– Fixed a bug where there was a misspelling within a code comment in the index.php file.
– Added Session Class userdata to the output profiler. Additionally, added a show/hide toggle on HTTP
Headers, Session Data and Config Variables.
– Removed internal usage of the EXT constant.
– Visual updates to the welcome_message view file and default error templates. Thanks to danijelb for the
pull request.
– Added insert_batch() function to the PostgreSQL database driver. Thanks to epallerols for the patch.
– Added “application/x-csv” to mimes.php.
– Fixed a bug where Email library attachments with a ”.” in the name would using invalid MIME-types.
• Helpers
– Added an optional third parameter to heading() which allows adding html attributes to the rendered heading
tag.
– form_open() now only adds a hidden (Cross-site Reference Forgery) protection field when the form’s
action is internal and is set to the post method. (Reactor #165)
– Re-worked plural() and singular() functions in the Inflector helper to support considerably more words.
• Libraries
– Altered Session to use a longer match against the user_agent string. See upgrade notes if using database
sessions.
– Added $this->db->set_dbprefix() to the Database Driver.
– Changed $this->cart->insert() in the Cart Library to return the Row ID if a single item was inserted successfully.
– Added $this->load->get_var() to the Loader library to retrieve global vars set with $this->load->view()
and $this->load->vars().
– Changed $this->db->having() to insert quotes using escape() rather than escape_str().
Bug fixes for 2.0.3
• Added ENVIRONMENT to reserved constants. (Reactor #196)
• Changed server check to ensure SCRIPT_NAME is defined. (Reactor #57)
294
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Removed APPPATH.’third_party’ from the packages autoloader to negate needless file stats if no packages exist
or if the developer does not load any other packages by default.
• Fixed a bug (Reactor #231) where Sessions Library database table example SQL did not contain an index on
last_activity. See Upgrade Notes.
• Fixed a bug (Reactor #229) where the Sessions Library example SQL in the documentation contained incorrect
SQL.
• Fixed a bug (Core #340) where when passing in the second parameter to $this->db->select(), column names in
subsequent queries would not be properly escaped.
• Fixed issue #199 - Attributes passed as string does not include a space between it and the opening tag.
• Fixed a bug where the method $this->cart->total_items() from Cart Library now returns the sum of the quantity
of all items in the cart instead of your total count.
• Fixed a bug where not setting ‘null’ when adding fields in db_forge for mysql and mysqli drivers would default
to NULL instead of NOT NULL as the docs suggest.
• Fixed a bug where using $this->db->select_max(), $this->db->select_min(), etc could throw notices. Thanks to
w43l for the patch.
• Replace checks for STDIN with php_sapi_name() == ‘cli’ which on the whole is more reliable. This should get
parameters in crontab working.
10.5.8 Version 2.0.2
Release Date: April 7, 2011 Hg Tag: v2.0.2
• General changes
– The Security library was moved to the core and is now loaded automatically. Please remove your loading
calls.
– The CI_SHA class is now deprecated. All supported versions of PHP provide a sha1() function.
– constants.php will now be loaded from the environment folder if available.
– Added language key error logging
– Made Environment Support optional. Comment out or delete the constant to stop environment checks.
– Added Environment Support for Hooks.
– Added CI_ Prefix to the Cache driver.
– Added CLI usage documentation.
• Helpers
– Removed the previously deprecated dohash() from the Security helper; use do_hash() instead.
– Changed the ‘plural’ function so that it doesn’t ruin the captalization of your string. It also take into
consideration acronyms which are all caps.
• Database
– $this->db->count_all_results() will now return an integer instead of a string.
10.5. Change Log
295
CodeIgniter Documentation, 3.0-dev
Bug fixes for 2.0.2
• Fixed a bug (Reactor #145) where the Output Library had parse_exec_vars set to protected.
• Fixed a bug (Reactor #80) where is_really_writable would create an empty file when on Windows or with
safe_mode enabled.
• Fixed various bugs with User Guide.
• Added is_cli_request() method to documentation for Input class.
• Added form_validation_lang entries for decimal, less_than and greater_than.
• Fixed issue #153 Escape Str Bug in MSSQL driver.
• Fixed issue #172 Google Chrome 11 posts incorrectly when action is empty.
10.5.9 Version 2.0.1
Release Date: March 15, 2011 Hg Tag: v2.0.1
• General changes
– Added $config[’cookie_secure’] to the config file to allow requiring a secure (HTTPS) in order to set
cookies.
– Added the constant CI_CORE to help differentiate between Core: TRUE and Reactor: FALSE.
– Added an ENVIRONMENT constant in index.php, which affects PHP error reporting settings, and optionally, which configuration files are loaded (see below). Read more on the Handling Environments page.
– Added support for environment-specific configuration files.
• Libraries
– Added decimal, less_than and greater_than rules to the Form validation Class.
– Input Class methods post() and get() will now return a full array if the first argument is not provided.
– Secure cookies can now be made with the set_cookie() helper and Input Class method.
– Added set_content_type() to Output Class to set the output Content-Type HTTP header based on a MIME
Type or a config/mimes.php array key.
– Output Class will now support method chaining.
• Helpers
– Changed the logic for form_open() in Form helper. If no value is passed it will submit to the current URL.
Bug fixes for 2.0.1
• CLI requests can now be run from any folder, not just when CD’ed next to index.php.
• Fixed issue #41: Added audio/mp3 mime type to mp3.
• Fixed a bug (Core #329) where the file caching driver referenced the incorrect cache directory.
• Fixed a bug (Reactor #69) where the SHA1 library was named incorrectly.
296
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
10.5.10 Version 2.0.0
Release Date: January 28, 2011 Hg Tag: v2.0.0
• General changes
– PHP 4 support is removed. CodeIgniter now requires PHP 5.1.6.
– Scaffolding, having been deprecated for a number of versions, has been removed.
– Plugins have been removed, in favor of Helpers. The CAPTCHA plugin has been converted to a Helper and
documented. The JavaScript calendar plugin was removed due to the ready availability of great JavaScript
calendars, particularly with jQuery.
– Added new special Library type: Drivers.
– Added full query-string support. See the config file for details.
– Moved the application folder outside of the system folder.
– Moved system/cache and system/logs directories to the application directory.
– Added routing overrides to the main index.php file, enabling the normal routing to be overridden on a per
“index” file basis.
– Added the ability to set config values (or override config values) directly from data set in the main index.php file. This allows a single application to be used with multiple front controllers, each having its
own config values.
– Added $config[’directory_trigger’] to the config file so that a controller sub-directory can be specified
when running _GET strings instead of URI segments.
– Added ability to set “Package” paths - specific paths where the Loader and Config classes should try to
look first for a requested file. This allows distribution of sub-applications with their own libraries, models,
config files, etc. in a single “package” directory. See the Loader class documentation for more details.
– In-development code is now hosted at BitBucket.
– Removed the deprecated Validation Class.
– Added CI_ Prefix to all core classes.
– Package paths can now be set in application/config/autoload.php.
– Upload library file_name can now be set without an extension, the extension will be taken from the uploaded file instead of the given name.
– In Database Forge the name can be omitted from $this->dbforge->modify_column()’s 2nd param if you
aren’t changing the name.
– $config[’base_url’] is now empty by default and will guess what it should be.
– Enabled full Command Line Interface compatibility with config[’uri_protocol’] = ‘CLI’;.
• Libraries
– Added a Cache driver with APC, memcached, and file-based support.
– Added $prefix, $suffix and $first_url properties to Pagination library.
– Added the ability to suppress first, previous, next, last, and page links by setting their values to FALSE in
the Pagination library.
– Added Security library, which now contains the xss_clean function, filename_security function and other
security related functions.
– Added CSRF (Cross-site Reference Forgery) protection to the Security library.
10.5. Change Log
297
CodeIgniter Documentation, 3.0-dev
– Added $parse_exec_vars property to Output library.
– Added ability to enable / disable individual sections of the Profiler
– Added a wildcard option $config[’allowed_types’] = ‘*’ to the File Uploading Class.
– Added an ‘object’ config variable to the XML-RPC Server library so that one can specify the object to
look for requested methods, instead of assuming it is in the $CI superobject.
– Added “is_object” into the list of unit tests capable of being run.
– Table library will generate an empty cell with a blank string, or NULL value.
– Added ability to set tag attributes for individual cells in the Table library
– Added a parse_string() method to the Parser Class.
– Added HTTP headers and Config information to the Profiler output.
– Added Chrome and Flock to the list of detectable browsers by browser() in the User Agent Class.
– The Unit Test Class now has an optional “notes” field available to it, and allows for discrete display of test
result items using $this->unit->set_test_items().
– Added a $xss_clean class variable to the XMLRPC library, enabling control over the use of the Security
library’s xss_clean() method.
– Added a download() method to the FTP library
– Changed do_xss_clean() to return FALSE if the uploaded file fails XSS checks.
– Added stripslashes() and trim()ing of double quotes from $_FILES type value to standardize input in
Upload library.
– Added a second parameter (boolean) to $this->zip->read_dir(‘/path/to/directory’, FALSE) to remove the
preceding trail of empty folders when creating a Zip archive. This example would contain a zip with
“directory” and all of its contents.
– Added ability in the Image Library to handle PNG transparency for resize operations when using the GD
lib.
– Modified the Session class to prevent use if no encryption key is set in the config file.
– Added a new config item to the Session class sess_expire_on_close to allow sessions to auto-expire when
the browser window is closed.
– Improved performance of the Encryption library on servers where Mcrypt is available.
– Changed the default encryption mode in the Encryption library to CBC.
– Added an encode_from_legacy() method to provide a way to transition encrypted data from CodeIgniter
1.x to CodeIgniter 2.x. Please see the upgrade instructions for details.
– Altered Form_Validation library to allow for method chaining on set_rules(), set_message() and
set_error_delimiters() functions.
– Altered Email Library to allow for method chaining.
– Added request_headers(), get_request_header() and is_ajax_request() to the input class.
– Altered User agent library so that is_browser(), is_mobile() and is_robot() can optionally check for a
specific browser or mobile device.
– Altered Input library so that post() and get() will return all POST and GET items (respectively) if there are
no parameters passed in.
• Database
298
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
– database configuration.
– Added autoinit value to database configuration.
– Added stricton value to database configuration.
– Added database_exists() to the Database Utilities Class.
– Semantic change to db->version() function to allow a list of exceptions for databases with functions to
return version string instead of specially formed SQL queries. Currently this list only includes Oracle and
SQLite.
– Fixed a bug where driver specific table identifier protection could lead to malformed queries in the
field_data() functions.
– Fixed a bug where an undefined class variable was referenced in database drivers.
– Modified the database errors to show the filename and line number of the problematic query.
– Removed the following deprecated functions: orwhere, orlike, groupby, orhaving, orderby, getwhere.
– Removed deprecated _drop_database() and _create_database() functions from the db utility drivers.
– Improved dbforge create_table() function for the Postgres driver.
• Helpers
– Added convert_accented_characters() function to text helper.
– Added accept-charset to the list of inserted attributes of form_open() in the Form Helper.
– Deprecated the dohash() function in favour of do_hash() for naming consistency.
– Non-backwards compatible change made to get_dir_file_info() in the File Helper. No longer recurses by
default so as to encourage responsible use (this function can cause server performance issues when used
without caution).
– Modified the second parameter of directory_map() in the Directory Helper to accept an integer to specify
recursion depth.
– Modified delete_files() in the File Helper to return FALSE on failure.
– Added an optional second parameter to byte_format() in the Number Helper to allow for decimal precision.
– Added alpha, and sha1 string types to random_string() in the String Helper.
– Modified prep_url() so as to not prepend http:// if the supplied string already has a scheme.
– Modified get_file_info in the file helper, changing filectime() to filemtime() for dates.
– Modified smiley_js() to add optional third parameter to return only the javascript with no script tags.
– The img() function of the HTML helper will now generate an empty string as an alt attribute if one is not
provided.
– If CSRF is enabled in the application config file, form_open() will automatically insert it as a hidden field.
– Added sanitize_filename() into the Security helper.
– Added ellipsize() to the Text Helper
– Added elements() to the Array Helper
• Other Changes
– Added an optional second parameter to show_404() to disable logging.
– Updated loader to automatically apply the sub-class prefix as an option when loading classes. Class names
can be prefixed with the standard “CI_” or the same prefix as the subclass prefix, or no prefix at all.
10.5. Change Log
299
CodeIgniter Documentation, 3.0-dev
– Increased randomness with is_really_writable() to avoid file collisions when hundreds or thousands of
requests occur at once.
– Switched some DIR_WRITE_MODE constant uses to FILE_WRITE_MODE where files and not directories are being operated on.
– get_mime_by_extension() is now case insensitive.
– Added “default” to the list Reserved Names.
– Added ‘application/x-msdownload’ for .exe files and ‘application/x-gzip-compressed’ for .tgz files to config/mimes.php.
– Updated the output library to no longer compress output or send content-length headers if the server runs
with zlib.output_compression enabled.
– Eliminated a call to is_really_writable() on each request unless it is really needed (Output caching)
– Documented append_output() in the Output Class.
– Documented a second argument in the decode() function for the Encryption Class.
– Documented db->close().
– Updated the router to support a default route with any number of segments.
– Moved _remove_invisible_characters() function from the Security Library to common functions.
– Added audio/mpeg3 as a valid mime type for MP3.
Bug fixes for 2.0.0
• Fixed a bug where you could not change the User-Agent when sending email.
• Fixed a bug where the Output class would send incorrect cached output for controllers implementing their own
_output() method.
• Fixed a bug where a failed query would not have a saved query execution time causing errors in the Profiler
• Fixed a bug that was writing log entries when multiple identical helpers and plugins were loaded.
• Fixed assorted user guide typos or examples (#10693, #8951, #7825, #8660, #7883, #6771, #10656).
• Fixed a language key in the profiler: “profiler_no_memory_usage” to “profiler_no_memory”.
• Fixed an error in the Zip library that didn’t allow downloading on PHP 4 servers.
• Fixed a bug in the Form Validation library where fields passed as rule parameters were not being translated
(#9132)
• Modified inflector helper to properly pluralize words that end in ‘ch’ or ‘sh’
• Fixed a bug in xss_clean() that was not allowing hyphens in query strings of submitted URLs.
• Fixed bugs in get_dir_file_info() and get_file_info() in the File Helper with recursion, and file paths on Windows.
• Fixed a bug where Active Record override parameter would not let you disable Active Record if it was enabled
in your database config file.
• Fixed a bug in reduce_double_slashes() in the String Helper to properly remove duplicate leading slashes
(#7585)
• Fixed a bug in values_parsing() of the XML-RPC library which prevented NULL variables typed as ‘string’
from being handled properly.
• Fixed a bug were form_open_multipart() didn’t accept string attribute arguments (#10930).
300
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Fixed a bug (#10470) where get_mime_by_extension() was case sensitive.
• Fixed a bug where some error messages for the SQLite and Oracle drivers would not display.
• Fixed a bug where files created with the Zip Library would result in file creation dates of 1980.
• Fixed a bug in the Session library that would result in PHP error when attempting to store values with objects.
• Fixed a bug where extending the Controller class would result in a fatal PHP error.
• Fixed a PHP Strict Standards Error in the index.php file.
• Fixed a bug where getimagesize() was being needlessly checked on non-image files in is_allowed_type().
• Fixed a bug in the Encryption library where an empty key was not triggering an error.
• Fixed a bug in the Email library where CC and BCC recipients were not reset when using the clear() method
(#109).
• Fixed a bug in the URL Helper where prep_url() could cause a PHP error on PHP versions < 5.1.2.
• Added a log message in core/output if the cache directory config value was not found.
• Fixed a bug where multiple libraries could not be loaded by passing an array to load->library()
• Fixed a bug in the html helper where too much white space was rendered between the src and alt tags in the
img() function.
• Fixed a bug in the profilers _compile_queries() function.
• Fixed a bug in the date helper where the DATE_ISO8601 variable was returning an incorrectly formatted date
string.
10.5.11 Version 1.7.2
Release Date: September 11, 2009 Hg Tag: v1.7.2
• Libraries
– Added a new Cart Class.
– Added the ability to pass $config[’file_name’] for the File Uploading Class and rename the uploaded file.
– Changed order of listed user-agents so Safari would more accurately report itself. (#6844)
• Database
– Switched from using gettype() in escape() to is_* methods, since future PHP versions might change its
output.
– Updated all database drivers to handle arrays in escape_str()
– Added escape_like_str() method for escaping strings to be used in LIKE conditions
– Updated Active Record to utilize the new LIKE escaping mechanism.
– Added reconnect() method to DB drivers to try to keep alive / reestablish a connection after a long idle.
– Modified MSSQL driver to use mssql_get_last_message() for error messages.
• Helpers
– Added form_multiselect() to the Form helper.
– Modified form_hidden() in the Form helper to accept multi-dimensional arrays.
10.5. Change Log
301
CodeIgniter Documentation, 3.0-dev
– Modified form_prep() in the Form helper to keep track of prepped fields to avoid multiple prep/mutation
from subsequent calls which can occur when using Form Validation and form helper functions to output
form fields.
– Modified directory_map() in the Directory helper to allow the inclusion of hidden files, and to return
FALSE on failure to read directory.
– Modified the Smiley helper to work with multiple fields and insert the smiley at the last known cursor
position.
• General
– Compatible with PHP 5.3.0.
– Modified show_error() to allow sending of HTTP server response codes.
– Modified show_404() to send 404 status code, removing non-CGI compatible header() statement from
error_404.php template.
– Added set_status_header() to the Common functions to allow use when the Output class is unavailable.
– Added is_php() to Common functions to facilitate PHP version comparisons.
– Added 2 CodeIgniter “cheatsheets” (thanks to DesignFellow.com for this contribution).
Bug fixes for 1.7.2
• Fixed assorted user guide typos or examples (#6743, #7214, #7516, #7287, #7852, #8224, #8324, #8349).
• Fixed a bug in the Form Validation library where multiple callbacks weren’t working (#6110)
• doctype helper default value was missing a “1”.
• Fixed a bug in the language class when outputting an error for an unfound file.
• Fixed a bug in the Calendar library where the shortname was output for “May”.
• Fixed a bug with ORIG_PATH_INFO that was allowing URIs of just a slash through.
• Fixed a fatal error in the Oracle and ODBC drivers (#6752)
• Fixed a bug where xml_from_result() was checking for a nonexistent method.
• Fixed a bug where Database Forge’s add_column and modify_column were not looping through when sent
multiple fields.
• Fixed a bug where the File Helper was using ‘/’ instead of the DIRECTORY_SEPARATOR constant.
• Fixed a bug to prevent PHP errors when attempting to use sendmail on servers that have manually disabled the
PHP popen() function.
• Fixed a bug that would cause PHP errors in XML-RPC data if the PHP data type did not match the specified
XML-RPC type.
• Fixed a bug in the XML-RPC class with parsing dateTime.iso8601 data types.
• Fixed a case sensitive string replacement in xss_clean()
• Fixed a bug in form_textarea() where form data was not prepped correctly.
• Fixed a bug in form_prep() causing it to not preserve entities in the user’s original input when called back into
a form element
• Fixed a bug in _protect_identifiers() where the swap prefix ($swap_pre) was not being observed.
302
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Fixed a bug where the 400 status header sent with the ‘disallowed URI characters’ was not compatible with CGI
environments.
• Fixed a bug in the typography class where heading tags could have paragraph tags inserted when using
auto_typography().
10.5.12 Version 1.7.1
Release Date: February 10, 2009 Hg Tag: 1.7.1
• Libraries
– Fixed an arbitrary script execution security flaw (#6068) in the Form Validation library (thanks to hkk)
– Changed default current page indicator in the Pagination library to use <strong> instead of <b>
– A “HTTP/1.1 400 Bad Request” header is now sent when disallowed characters are encountered.
– Added <big>, <small>, <q>, and <tt> to the Typography parser’s inline elements.
– Added more accurate error reporting for the Email library when using sendmail.
– Removed a strict type check from the rotate() function of the Image Manipulation Class.
– Added enhanced error checking in file saving in the Image library when using the GD lib.
– Added an additional newline between multipart email headers and the MIME message text for better
compatibility with a variety of MUAs.
– Made modest improvements to efficiency and accuracy of explode_name() in the Image lib.
• Database
– Added where_in to the list of expected arguments received by delete().
• Helpers
– Added the ability to have optgroups in form_dropdown() within the form helper.
– Added a doctype() function to the HTML helper.
– Added ability to force lowercase for url_title() in the URL helper.
– Changed the default “type” of form_button() to “button” from “submit” in the form helper.
– Changed redirect() in the URL helper to allow redirections to URLs outside of the CI site.
– Updated get_cookie() to try to fetch the cookie using the global cookie prefix if the requested cookie name
doesn’t exist.
• Other Changes
– Improved security in xss_clean() to help prevent attacks targeting Internet Explorer.
– Added ‘application/msexcel’ to config/mimes.php for .xls files.
– Added ‘proxy_ips’ config item to whitelist reverse proxy servers from which to trust the
HTTP_X_FORWARDED_FOR header to to determine the visitor’s IP address.
– Improved accuracy of Upload::is_allowed_filetype() for images (#6715)
10.5. Change Log
303
CodeIgniter Documentation, 3.0-dev
Bug fixes for 1.7.1
• Database
– Fixed a bug when doing ‘random’ on order_by() (#5706).
– Fixed a bug where adding a primary key through Forge could fail (#5731).
– Fixed a bug when using DB cache on multiple databases (#5737).
– Fixed a bug where TRUNCATE was not considered a “write” query (#6619).
– Fixed a bug where csv_from_result() was checking for a nonexistent method.
– Fixed a bug _protect_identifiers() where it was improperly removing all pipe symbols from items
• Fixed assorted user guide typos or examples (#5998, #6093, #6259, #6339, #6432, #6521).
• Fixed a bug in the MySQLi driver when no port is specified
• Fixed a bug (#5702), in which the field label was not being fetched properly, when “matching” one field to
another.
• Fixed a bug in which identifers were not being escaped properly when reserved characters were used.
• Fixed a bug with the regular expression used to protect submitted paragraph tags in auto typography.
• Fixed a bug where double dashes within tag attributes were being converted to em dash entities.
• Fixed a bug where double spaces within tag attributes were being converted to non-breaking space entities.
• Fixed some accuracy issues with curly quotes in Typography::format_characters()
• Changed a few docblock comments to reflect actual return values.
• Fixed a bug with high ascii characters in subject and from email headers.
• Fixed a bug in xss_clean() where whitespace following a validated character entity would not be preserved.
• Fixed a bug where HTML comments and <pre> tags were being parsed in Typography::auto_typography().
• Fixed a bug with non-breaking space cleanup in Typography::auto_typography().
• Fixed a bug in database escaping where a compound statement (ie: SUM()) wasn’t handled correctly with
database prefixes.
• Fixed a bug when an opening quote is preceded by a paragraph tag and immediately followed by another tag.
• Fixed a bug in the Text Helper affecting some locales where word_censor() would not work on words beginning
or ending with an accented character.
• Fixed a bug in the Text Helper character limiter where the provided limit intersects the last word of the string.
• Fixed a bug (#6342) with plural() in the Inflection helper with words ending in “y”.
• Fixed bug (#6517) where Routed URI segments returned by URI::rsegment() method were incorrect for the
default controller.
• Fixed a bug (#6706) in the Security Helper where xss_clean() was using a deprecated second argument.
• Fixed a bug in the URL helper url_title() function where trailing periods were allowed at the end of a URL.
• Fixed a bug (#6669) in the Email class when CRLF’s are used for the newline character with headers when used
with the “mail” protocol.
• Fixed a bug (#6500) where URI::A_filter_uri() was exit()ing an error instead of using show_error().
• Fixed a bug (#6592) in the File Helper where get_dir_file_info() where recursion was not occurring properly.
304
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Tweaked Typography::auto_typography() for some edge-cases.
10.5.13 Version 1.7
Release Date: October 23, 2008 Hg Tag: 1.7.0
• Libraries
– Added a new Form Validation Class. It simplifies setting rules and field names, supports arrays as field
names, allows groups of validation rules to be saved in a config file, and adds some helper functions for
use in view files. Please note that the old Validation class is now deprecated. We will leave it in the
library folder for some time so that existing applications that use it will not break, but you are encouraged
to migrate to the new version.
– Updated the Sessions class so that any custom data being saved gets stored to a database rather than the
session cookie (assuming you are using a database to store session data), permitting much more data to be
saved.
– Added the ability to store libraries in subdirectories within either the main “libraries” or the local application “libraries” folder. Please see the Loader class for more info.
– Added the ability to assign library objects to your own variable names when you use $this->load->library().
Please see the Loader class for more info.
– Added controller class/method info to Profiler class and support for multiple database connections.
– Improved the “auto typography” feature and moved it out of the helper into its own Typography Class.
– Improved performance and accuracy of xss_clean(), including reduction of false positives on image/file
tests.
– Improved Parser class to allow multiple calls to the parse() function. The output of each is appended in
the output.
– Added max_filename option to set a file name length limit in the File Upload Class.
– Added set_status_header() function to Output class.
– Modified Pagination class to only output the “First” link when the link for page one would not be shown.
– Added support for mb_strlen in the Form Validation class so that multi-byte languages will calculate string
lengths properly.
• Database
– Improved Active Record class to allow full path column and table names: hostname.database.table.column.
Also improved the alias handling.
– Improved how table and column names are escaped and prefixed. It now honors full path names when
adding prefixes and escaping.
– Added Active Record caching feature to “update” and “delete” functions.
– Added removal of non-printing control characters in escape_str() of DB drivers that do not have native
PHP escaping mechanisms (mssql, oci8, odbc), to avoid potential SQL errors, and possible sources of
SQL injection.
– Added port support to MySQL, MySQLi, and MS SQL database drivers.
– Added driver name variable in each DB driver, based on bug report #4436.
• Helpers
10.5. Change Log
305
CodeIgniter Documentation, 3.0-dev
– Added several new “setting” functions to the Form helper that allow POST data to be retrieved and set into
forms. These are intended to be used on their own, or with the new Form Validation Class.
– Added current_url() and uri_segments() to URL helper.
– Altered auto_link() in the URL helper so that email addresses with “+” included will be linked.
– Added meta() function to HTML helper.
– Improved accuracy of calculations in Number helper.
– Removed added newlines (“\n”) from most form and html helper functions.
– Tightened up validation in the Date helper function human_to_unix(), and eliminated the POSIX regex.
– Updated Date helper to match the world’s current time zones and offsets.
– Modified url_title() in the URL helper to remove characters and digits that are part of character entities, to
allow dashes, underscores, and periods regardless of the $separator, and to allow uppercase characters.
– Added support for arbitrary attributes in anchor_popup() of the URL helper.
• Other Changes
– Added PHP Style Guide to docs.
– Added sanitization in xss_clean() for a deprecated HTML tag that could be abused in user input in Internet
Explorer.
– Added a few openxml document mime types, and an additional mobile agent to mimes.php and
user_agents.php respectively.
– Added a file lock check during caching, before trying to write to the file.
– Modified Cookie key cleaning to unset a few troublesome key names that can be present in certain environments, preventing CI from halting execution.
– Changed the output of the profiler to use style attribute rather than clear, and added the id
“codeigniter_profiler” to the container div.
Bug fixes for 1.7.0
• Fixed bug in xss_clean() that could remove some desirable tag attributes.
• Fixed assorted user guide typos or examples (#4807, #4812, #4840, #4862, #4864, #4899, #4930, #5006, #5071,
#5158, #5229, #5254, #5351).
• Fixed an edit from 1.6.3 that made the $robots array in user_agents.php go poof.
• Fixed a bug in the Email library with quoted-printable encoding improperly encoding space and tab characters.
• Modified XSS sanitization to no longer add semicolons after &[single letter], such as in M&M’s, B&B, etc.
• Modified XSS sanitization to no longer strip XHTML image tags of closing slashes.
• Fixed a bug in the Session class when database sessions are used where upon session update all userdata would
be errantly written to the session cookie.
• Fixed a bug (#4536) in backups with the MySQL driver where some legacy code was causing certain characters
to be double escaped.
• Fixed a routing bug (#4661) that occurred when the default route pointed to a subfolder.
• Fixed the spelling of “Dhaka” in the timezone_menu() function of the Date helper.
• Fixed the spelling of “raspberry” in config/smileys.php.
306
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Fixed incorrect parenthesis in form_open() function (#5135).
• Fixed a bug that was ignoring case when comparing controller methods (#4560).
• Fixed a bug (#4615) that was not setting SMTP authorization settings when using the initialize function.
• Fixed a bug in highlight_code() in the Text helper that would leave a stray </span> in certain cases.
• Fixed Oracle bug (#3306) that was preventing multiple queries in one action.
• Fixed ODBC bug that was ignoring connection params due to its use of a constructor.
• Fixed a DB driver bug with num_rows() that would cause an error with the Oracle driver.
• Fixed MS SQL bug (#4915). Added brackets around database name in MS SQL driver when selecting the
database, in the event that reserved characters are used in the name.
• Fixed a DB caching bug (4718) in which the path was incorrect when no URI segments were present.
• Fixed Image_lib class bug #4562. A path was not defined for NetPBM.
• Fixed Image_lib class bug #4532. When cropping an image with identical height/width settings on output, a
copy is made.
• Fixed DB_driver bug (4900), in which a database error was not being logged correctly.
• Fixed DB backup bug in which field names were not being escaped.
• Fixed a DB Active Record caching bug in which multiple calls to cached data were not being honored.
• Fixed a bug in the Session class that was disallowing slashes in the serialized array.
• Fixed a Form Validation bug in which the “isset” error message was being trigged by the “required” rule.
• Fixed a spelling error in a Loader error message.
• Fixed a bug (5050) with IP validation with empty segments.
• Fixed a bug in which the parser was being greedy if multiple identical sets of tags were encountered.
10.5.14 Version 1.6.3
Release Date: June 26, 2008 Hg Tag: v1.6.3
Version 1.6.3 is a security and maintenance release and is recommended for all users.
• Database
– Modified MySQL/MySQLi Forge class to give explicit names to keys
– Added ability to set multiple column non-primary keys to the Forge class
– Added ability to set additional database config values in DSN connections via the query string.
• Libraries
– Set the mime type check in the Upload class to reference the global mimes variable.
– Added support for query strings to the Pagination class, automatically detected or explicitly declared.
– Added get_post() to the Input class.
– Documented get() in the Input class.
– Added the ability to automatically output language items as form labels in the Language class.
• Helpers
– Added a Language helper.
10.5. Change Log
307
CodeIgniter Documentation, 3.0-dev
– Added a Number helper.
– Form helper refactored to allow form_open() and form_fieldset() to accept arrays or strings as arguments.
• Other changes
– Improved security in xss_clean().
– Removed an unused Router reference in _display_cache().
– Added ability to use xss_clean() to test images for XSS, useful for upload security.
– Considerably expanded list of mobile user-agents in config/user_agents.php.
– Charset information in the userguide has been moved above title for internationalization purposes (#4614).
– Added “Using Associative Arrays In a Request Parameter” example to the XMLRPC userguide page.
– Removed maxlength and size as automatically added attributes of form_input() in the form helper.
– Documented the language file use of byte_format() in the number helper.
Bug fixes for 1.6.3
• Added a language key for valid_emails in validation_lang.php.
• Amended fixes for bug (#3419) with parsing DSN database connections.
• Moved the _has_operator() function (#4535) into DB_driver from DB_active_rec.
• Fixed a syntax error in upload_lang.php.
• Fixed a bug (#4542) with a regular expression in the Image library.
• Fixed a bug (#4561) where orhaving() wasn’t properly passing values.
• Removed some unused variables from the code (#4563).
• Fixed a bug where having() was not adding an = into the statement (#4568).
• Fixed assorted user guide typos or examples (#4574, #4706).
• Added quoted-printable headers to Email class when the multi-part override is used.
• Fixed a double opening <p> tag in the index pages of each system directory.
10.5.15 Version 1.6.2
Release Date: May 13, 2008 Hg Tag: 1.6.2
• Active Record
– Added the ability to prevent escaping in having() clauses.
– Added rename_table() into DBForge.
– Fixed a bug that wasn’t allowing escaping to be turned off if the value of a query was NULL.
– DB Forge is now assigned to any models that exist after loading (#3457).
• Database
– Added Strict Mode to database transactions.
– Escape behaviour in where() clauses has changed; values in those with the “FALSE” argument are no
longer escaped (ie: quoted).
308
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Config
– Added ‘application/vnd.ms-powerpoint’ to list of mime types.
– Added ‘audio/mpg’ to list of mime types.
– Added new user-modifiable file constants.php containing file mode and fopen constants.
– Added the ability to set CRLF settings via config in the Email class.
• Libraries
– Added increased security for filename handling in the Upload library.
– Added increased security for sessions for client-side data tampering.
– The MySQLi forge class is now in sync with MySQL forge.
– Added the ability to set CRLF settings via config in the Email class.
– Unit Testing results are now colour coded, and a change was made to the default template of results.
– Added a valid_emails rule to the Validation class.
– The Zip class now exits within download().
– The Zip class has undergone a substantial re-write for speed and clarity (thanks stanleyxu for the hard
work and code contribution in bug report #3425!)
• Helpers
– Added a Compatibility Helper for using some common PHP 5 functions safely in applications that might
run on PHP 4 servers (thanks Seppo for the hard work and code contribution!)
– Added form_button() in the Form helper.
– Changed the radio() and checkbox() functions to default to not checked by default.
– Added the ability to include an optional HTTP Response Code in the redirect() function of the URL Helper.
– Modified img() in the HTML Helper to remove an unneeded space (#4208).
– Modified anchor() in the URL helper to no longer add a default title= attribute (#4209).
– The Download helper now exits within force_download().
– Added get_dir_file_info(), get_file_info(), and get_mime_by_extension() to the File Helper.
– Added symbolic_permissions() and octal_permissions() to the File helper.
• Plugins
– Modified captcha generation to first look for the function imagecreatetruecolor, and fallback to imagecreate
if it isn’t available (#4226).
• Other Changes
– Added ability for xss_clean() to accept arrays.
– Removed closing PHP tags from all PHP files to avoid accidental output and potential ‘cannot modify
headers’ errors.
– Removed “scripts” from the auto-load search path. Scripts were deprecated in Version 1.4.1 (September
21, 2006). If you still need to use them for legacy reasons, they must now be manually loaded in each
Controller.
– Added a Reserved Names page to the userguide, and migrated reserved controller names into it.
– Added a Common Functions page to the userguide for globally available functions.
10.5. Change Log
309
CodeIgniter Documentation, 3.0-dev
– Improved security and performance of xss_clean().
Bugfixes for 1.6.2
• Fixed a bug where SET queries were not being handled as “write” queries.
• Fixed a bug (#3191) with ORIG_PATH_INFO URI parsing.
• Fixed a bug in DB Forge, when inserting an id field (#3456).
• Fixed a bug in the table library that could cause identically constructed rows to be dropped (#3459).
• Fixed DB Driver and MySQLi result driver checking for resources instead of objects (#3461).
• Fixed an AR_caching error where it wasn’t tracking table aliases (#3463).
• Fixed a bug in AR compiling, where select statements with arguments got incorrectly escaped (#3478).
• Fixed an incorrect documentation of $this->load->language (#3520).
• Fixed bugs (#3523, #4350) in get_filenames() with recursion and problems with Windows when $include_path
is used.
• Fixed a bug (#4153) in the XML-RPC class preventing dateTime.iso8601 from being used.
• Fixed an AR bug with or_where_not_in() (#4171).
• Fixed a bug with xss_clean() that would add semicolons to GET URI variable strings.
• Fixed a bug (#4206) in the Directory Helper where the directory resource was not being closed, and minor
improvements.
• Fixed a bug in the FTP library where delete_dir() was not working recursively (#4215).
• Fixed a Validation bug when set_rules() is used with a non-array field name and rule (#4220).
• Fixed a bug (#4223) where DB caching would not work for returned DB objects or multiple DB connections.
• Fixed a bug in the Upload library that might output the same error twice (#4390).
• Fixed an AR bug when joining with a table alias and table prefix (#4400).
• Fixed a bug in the DB class testing the $params argument.
• Fixed a bug in the Table library where the integer 0 in cell data would be displayed as a blank cell.
• Fixed a bug in link_tag() of the URL helper where a key was passed instead of a value.
• Fixed a bug in DB_result::row() that prevented it from returning individual fields with MySQL NULL values.
• Fixed a bug where SMTP emails were not having dot transformation performed on lines that begin with a dot.
• Fixed a bug in display_error() in the DB driver that was instantiating new Language and Exception objects, and
not using the error heading.
• Fixed a bug (#4413) where a URI containing slashes only e.g. ‘http://example.com/index.php?//‘ would result
in PHP errors
• Fixed an array to string conversion error in the Validation library (#4425)
• Fixed bug (#4451, #4299, #4339) where failed transactions will not rollback when debug mode is enabled.
• Fixed a bug (#4506) with overlay_watermark() in the Image library preventing support for PNG-24s with alpha
transparency
• Fixed assorted user guide typos (#3453, #4364, #4379, #4399, #4408, #4412, #4448, #4488).
310
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
10.5.16 Version 1.6.1
Release Date: February 12, 2008 Hg Tag: 1.6.1
• Active Record
– Added Active Record Caching.
– Made Active Record fully database-prefix aware.
• Database drivers
– Added support for setting client character set and collation for MySQLi.
• Core Changes
– Modified xss_clean() to be more intelligent with its handling of URL encoded strings.
– Added $_SERVER, $_FILES, $_ENV, and $_SESSION to sanitization of globals.
– Added a Path Helper.
– Simplified _reindex_segments() in the URI class.
– Escaped the ‘-‘ in the default ‘permitted_uri_chars’ config item, to prevent errors if developers just try to
add additional characters to the end of the default expression.
– Modified method calling to controllers to show a 404 when a private or protected method is accessed via a
URL.
– Modified framework initiated 404s to log the controller and method for invalid requests.
• Helpers
– Modified get_filenames() in the File Helper to return FALSE if the $source_dir is not readable.
Bugfixes for 1.6.1
• Deprecated is_numeric as a validation rule. Use of numeric and integer are preferred.
• Fixed bug (#3379) in DBForge with SQLite for table creation.
• Made Active Record fully database prefix aware (#3384).
• Fixed a bug where DBForge was outputting invalid SQL in Postgres by adding brackets around the tables in
FROM.
• Changed the behaviour of Active Record’s update() to make the WHERE clause optional (#3395).
• Fixed a bug (#3396) where certain POST variables would cause a PHP warning.
• Fixed a bug in query binding (#3402).
• Changed order of SQL keywords in the Profiler $highlight array so OR would not be highlighted before ORDER
BY.
• Fixed a bug (#3404) where the MySQLi driver was testing if $this->conn_id was a resource instead of an object.
• Fixed a bug (#3419) connecting to a database via a DSN string.
• Fixed a bug (#3445) where the routed segment array was not re-indexed to begin with 1 when the default
controller is used.
• Fixed assorted user guide typos.
10.5. Change Log
311
CodeIgniter Documentation, 3.0-dev
10.5.17 Version 1.6.0
Release Date: January 30, 2008
• DBForge
– Added DBForge to the database tools.
– Moved create_database() and drop_database() into DBForge.
– Added add_field(), add_key(), create_table(), drop_table(), add_column(), drop_column(), modify_column() into DBForge.
• Active Record
– Added protect_identifiers() in Active Record.
– All AR queries are backticked if appropriate to the database.
– Added where_in(), or_where_in(), where_not_in(), or_where_not_in(), not_like() and or_not_like() to Active Record.
– Added support for limit() into update() and delete() statements in Active Record.
– Added empty_table() and truncate_table() to Active Record.
– Added the ability to pass an array of tables to the delete() statement in Active Record.
– Added count_all_results() function to Active Record.
– Added select_max(), select_min(), select_avg() and select_sum() to Active Record.
– Added the ability to use aliases with joins in Active Record.
– Added a third parameter to Active Record’s like() clause to control where the wildcard goes.
– Added a third parameter to set() in Active Record that withholds escaping data.
– Changed the behaviour of variables submitted to the where() clause with no values to auto set “IS NULL”
• Other Database Related
– MySQL driver now requires MySQL 4.1+
– Added $this->DB->save_queries variable to DB driver, enabling queries to get saved or not. Previously
they were always saved.
– Added $this->db->dbprefix() to manually add database prefixes.
– Added ‘random’ as an order_by() option , and removed “rand()” as a listed option as it was MySQL only.
– Added a check for NULL fields in the MySQL database backup utility.
– Added “constrain_by_prefix” parameter to db->list_table() function. If set to TRUE it will limit the result
to only table names with the current prefix.
– Deprecated from Active Record; getwhere() for get_where(); groupby() for group_by(); havingor() for
having_or(); orderby() for order_by; orwhere() for or_where(); and orlike() for or_like().
– Modified csv_from_result() to output CSV data more in the spirit of basic rules of RFC 4180.
– Added ‘char_set’ and ‘dbcollat’ database configuration settings, to explicitly set the client communication
properly.
– Removed ‘active_r’ configuration setting and replaced with a global $active_record setting, which is more
in harmony with the global nature of the behavior (#1834).
• Core changes
312
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
– Added ability to load multiple views, whose content will be appended to the output in the order loaded.
– Added the ability to auto-load Models.
– Reorganized the URI and Routes classes for better clarity.
– Added Compat.php to allow function overrides for older versions of PHP or PHP environments missing
certain extensions / libraries
– Added memory usage, GET, URI string data, and individual query execution time to Profiler output.
– Deprecated Scaffolding.
– Added is_really_writable() to Common.php to provide a cross-platform reliable method of testing
file/folder writability.
• Libraries
– Changed the load protocol of Models to allow for extension.
– Strengthened the Encryption library to help protect against man in the middle attacks when
MCRYPT_MODE_CBC mode is used.
– Added Flashdata variables, session_id regeneration and configurable session update times to the Session
class.
– Removed ‘last_visit’ from the Session class.
– Added a language entry for valid_ip validation error.
– Modified prep_for_form() in the Validation class to accept arrays, adding support for POST array validation (via callbacks only)
– Added an “integer” rule into the Validation library.
– Added valid_base64() to the Validation library.
– Documented clear() in the Image Processing library.
– Changed the behaviour of custom callbacks so that they no longer trigger the “required” rule.
– Modified Upload class $_FILES error messages to be more precise.
– Moved the safe mode and auth checks for the Email library into the constructor.
– Modified variable names in _ci_load() method of Loader class to avoid conflicts with view variables.
– Added a few additional mime type variations for CSV.
– Enabled the ‘system’ methods for the XML-RPC Server library, except for ‘system.multicall’ which is still
disabled.
• Helpers & Plugins
– Added link_tag() to the HTML helper.
– Added img() to the HTML helper.
– Added ability to “extend” Helpers.
– Added an email helper into core helpers.
– Added strip_quotes() function to string helper.
– Added reduce_multiples() function to string helper.
– Added quotes_to_entities() function to string helper.
– Added form_fieldset(), form_fieldset_close(), form_label(), and form_reset() function to form helper.
10.5. Change Log
313
CodeIgniter Documentation, 3.0-dev
– Added support for external urls in form_open().
– Removed support for db_backup in MySQLi due to incompatible functions.
– Javascript Calendar plugin now uses the months and days from the calendar language file, instead of hardcoded values, internationalizing it.
• Documentation Changes
– Added Writing Documentation section for the community to use in writing their own documentation.
– Added titles to all user manual pages.
– Added attributes into <html> of userguide for valid html.
– Added Zip Encoding Class to the table of contents of the userguide.
– Moved part of the userguide menu javascript to an external file.
– Documented distinct() in Active Record.
– Documented the timezones() function in the Date Helper.
– Documented unset_userdata in the Session class.
– Documented 2 config options to the Database configuration page.
Bug fixes for Version 1.6.0
• Fixed a bug (#1813) preventing using $CI->db in the same application with returned database objects.
• Fixed a bug (#1842) where the $this->uri->rsegments array would not include the ‘index’ method if routed to
the controller without an implicit method.
• Fixed a bug (#1872) where word_limiter() was not retaining whitespace.
• Fixed a bug (#1890) in csv_from_result() where content that included the delimiter would break the file.
• Fixed a bug (#2542)in the clean_email() method of the Email class to allow for non-numeric / non-sequential
array keys.
• Fixed a bug (#2545) in _html_entity_decode_callback() when ‘global_xss_filtering’ is enabled.
• Fixed a bug (#2668) in the parser class where numeric data was ignored.
• Fixed a bug (#2679) where the “previous” pagination link would get drawn on the first page.
• Fixed a bug (#2702) in _object_to_array that broke some types of inserts and updates.
• Fixed a bug (#2732) in the SQLite driver for PHP 4.
• Fixed a bug (#2754) in Pagination to scan for non-positive num_links.
• Fixed a bug (#2762) in the Session library where user agent matching would fail on user agents ending with a
space.
• Fixed a bug (#2784) $field_names[] vs $Ffield_names[] in postgres and sqlite drivers.
• Fixed a bug (#2810) in the typography helper causing extraneous paragraph tags when string contains tags.
• Fixed a bug (#2849) where arguments passed to a subfolder controller method would be incorrectly shifted,
dropping the 3rd segment value.
• Fixed a bug (#2858) which referenced a wrong variable in the Image class.
• Fixed a bug (#2875)when loading plugin files as _plugin. and not _pi.
• Fixed a bug (#2912) in get_filenames() in the File Helper where the array wasn’t cleared after each call.
314
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Fixed a bug (#2974) in highlight_phrase() that caused an error with slashes.
• Fixed a bug (#3003) in the Encryption Library to support modes other than MCRYPT_MODE_ECB
• Fixed a bug (#3015) in the User Agent library where more then 2 languages where not reported with languages().
• Fixed a bug (#3017) in the Email library where some timezones were calculated incorrectly.
• Fixed a bug (#3024) in which master_dim wasn’t getting reset by clear() in the Image library.
• Fixed a bug (#3156) in Text Helper highlight_code() causing PHP tags to be handled incorrectly.
• Fixed a bug (#3166) that prevented num_rows from working in Oracle.
• Fixed a bug (#3175) preventing certain libraries from working properly when autoloaded in PHP 4.
• Fixed a bug (#3267) in the Typography Helper where unordered list was listed “un.
• Fixed a bug (#3268) where the Router could leave ‘/’ as the path.
• Fixed a bug (#3279) where the Email class was sending the wrong Content-Transfer-Encoding for some character sets.
• Fixed a bug (#3284) where the rsegment array would not be set properly if the requested URI contained more
segments than the routed URI.
• Removed extraneous load of $CFG in _display_cache() of the Output class (#3285).
• Removed an extraneous call to loading models (#3286).
• Fixed a bug (#3310) with sanitization of globals in the Input class that could unset CI’s global variables.
• Fixed a bug (#3314) which would cause the top level path to be deleted in delete_files() of the File helper.
• Fixed a bug (#3328) where the smiley helper might return an undefined variable.
• Fixed a bug (#3330) in the FTP class where a comparison wasn’t getting made.
• Removed an unused parameter from Profiler (#3332).
• Fixed a bug in database driver where num_rows property wasn’t getting updated.
• Fixed a bug in the upload library when allowed_files wasn’t defined.
• Fixed a bug in word_wrap() of the Text Helper that incorrectly referenced an object.
• Fixed a bug in Validation where valid_ip() wasn’t called properly.
• Fixed a bug in Validation where individual error messages for checkboxes wasn’t supported.
• Fixed a bug in captcha calling an invalid PHP function.
• Fixed a bug in the cookie helper “set_cookie” function. It was not honoring the config settings.
• Fixed a bug that was making validation callbacks required even when not set as such.
• Fixed a bug in the XML-RPC library so if a type is specified, a more intelligent decision is made as to the default
type.
• Fixed an example of comma-separated emails in the email library documentation.
• Fixed an example in the Calendar library for Showing Next/Previous Month Links.
• Fixed a typo in the database language file.
• Fixed a typo in the image language file “suppor” to “support”.
• Fixed an example for XML RPC.
• Fixed an example of accept_charset() in the User Agent Library.
10.5. Change Log
315
CodeIgniter Documentation, 3.0-dev
• Fixed a typo in the docblock comments that had CodeIgniter spelled CodeIgnitor.
• Fixed a typo in the String Helper (uniquid changed to uniqid).
• Fixed typos in the email Language class (email_attachment_unredable, email_filed_smtp_login), and FTP Class
(ftp_unable_to_remame).
• Added a stripslashes() into the Upload Library.
• Fixed a series of grammatical and spelling errors in the language files.
• Fixed assorted user guide typos.
10.5.18 Version 1.5.4
Release Date: July 12, 2007
• Added custom Language files to the autoload options.
• Added stripslashes() to the _clean_input_data() function in the Input class when magic quotes is on so that data
will always be un-slashed within the framework.
• Added array to string into the profiler.
• Added some additional mime types in application/config/mimes.php.
• Added filename_security() method to Input library.
• Added some additional arguments to the Inflection helper singular() to compensate for words ending in “s”.
Also added a force parameter to pluralize().
• Added $config[’charset’] to the config file. Default value is ‘UTF-8’, used in some string handling functions.
• Fixed MSSQL insert_id().
• Fixed a logic error in the DB trans_status() function. It was incorrectly returning TRUE on failure and FALSE
on success.
• Fixed a bug that was allowing multiple load attempts on extended classes.
• Fixed a bug in the bootstrap file that was incorrectly attempting to discern the full server path even when it was
explicity set by the user.
• Fixed a bug in the escape_str() function in the MySQL driver.
• Fixed a typo in the Calendar library
• Fixed a typo in rpcs.php library
• Fixed a bug in the Zip library, providing PC Zip file compatibility with Mac OS X
• Fixed a bug in router that was ignoring the scaffolding route for optimization
• Fixed an IP validation bug.
• Fixed a bug in display of POST keys in the Profiler output
• Fixed a bug in display of queries with characters that would be interpreted as HTML in the Profiler output
• Fixed a bug in display of Email class print debugger with characters that would be interpreted as HTML in the
debugging output
• Fixed a bug in the Content-Transfer-Encoding of HTML emails with the quoted-printable MIME type
• Fixed a bug where one could unset certain PHP superglobals by setting them via GET or POST data
• Fixed an undefined function error in the insert_id() function of the PostgreSQL driver
316
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Fixed various doc typos.
• Documented two functions from the String helper that were missing from the user guide: trim_slashes() and
reduce_double_slashes().
• Docs now validate to XHTML 1 transitional
• Updated the XSS Filtering to take into account the IE expression() ability and improved certain deletions to
prevent possible exploits
• Modified the Router so that when Query Strings are Enabled, the controller trigger and function trigger values
are sanitized for filename include security.
• Modified the is_image() method in the Upload library to take into account Windows IE 6/7 eccentricities when
dealing with MIMEs
• Modified XSS Cleaning routine to be more performance friendly and compatible with PHP 5.2’s new PCRE
backtrack and recursion limits.
• Modified the URL Helper to type cast the $title as a string in case a numeric value is supplied
• Modified Form Helper form_dropdown() to type cast the keys and values of the options array as strings, allowing
numeric values to be properly set as ‘selected’
• Deprecated the use if is_numeric() in various places since it allows periods. Due to compatibility problems
with ctype_digit(), making it unreliable in some installations, the following regular expression was used instead:
preg_match(“/[^0-9]/”, $n)
• Deprecated: APPVER has been deprecated and replaced with CI_VERSION for clarity.
10.5.19 Version 1.5.3
Release Date: April 15, 2007
• Added array to string into the profiler
• Code Igniter references updated to CodeIgniter
• pMachine references updated to EllisLab
• Fixed a bug in the repeater function of string helper.
• Fixed a bug in ODBC driver
• Fixed a bug in result_array() that was returning an empty array when no result is produced.
• Fixed a bug in the redirect function of the url helper.
• Fixed an undefined variable in Loader
• Fixed a version bug in the Postgres driver
• Fixed a bug in the textarea function of the form helper for use with strings
• Fixed doc typos.
10.5.20 Version 1.5.2
Release Date: February 13, 2007
• Added subversion information to the downloads page.
• Added support for captions in the Table Library
10.5. Change Log
317
CodeIgniter Documentation, 3.0-dev
• Fixed a bug in the download_helper that was causing Internet Explorer to load rather than download
• Fixed a bug in the Active Record Join function that was not taking table prefixes into consideration.
• Removed unescaped variables in error messages of Input and Router classes
• Fixed a bug in the Loader that was causing errors on Libraries loaded twice. A debug message is now silently
made in the log.
• Fixed a bug in the form helper that gave textarea a value attribute
• Fixed a bug in the Image Library that was ignoring resizing the same size image
• Fixed some doc typos.
10.5.21 Version 1.5.1
Release Date: November 23, 2006
• Added support for submitting arrays of libraries in the $this->load->library function.
• Added support for naming custom library files in lower or uppercase.
• Fixed a bug related to output buffering.
• Fixed a bug in the active record class that was not resetting query data after a completed query.
• Fixed a bug that was suppressing errors in controllers.
• Fixed a problem that can cause a loop to occur when the config file is missing.
• Fixed a bug that occurred when multiple models were loaded with the third parameter set to TRUE.
• Fixed an oversight that was not unsetting globals properly in the input sanitize function.
• Fixed some bugs in the Oracle DB driver.
• Fixed an incorrectly named variable in the MySQLi result driver.
• Fixed some doc typos.
10.5.22 Version 1.5.0.1
Release Date: October 31, 2006
• Fixed a problem in which duplicate attempts to load helpers and classes were not being stopped.
• Fixed a bug in the word_wrap() helper function.
• Fixed an invalid color Hex number in the Profiler class.
• Fixed a corrupted image in the user guide.
10.5.23 Version 1.5.0
Release Date: October 30, 2006
• Added DB utility class, permitting DB backups, CVS or XML files from DB results, and various other functions.
• Added Database Caching Class.
• Added transaction support to the database classes.
318
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Added Profiler Class which generates a report of Benchmark execution times, queries, and POST data at the
bottom of your pages.
• Added User Agent Library which allows browsers, robots, and mobile devises to be identified.
• Added HTML Table Class , enabling tables to be generated from arrays or database results.
• Added Zip Encoding Library.
• Added FTP Library.
• Added the ability to extend libraries and extend core classes, in addition to being able to replace them.
• Added support for storing models within sub-folders.
• Added Download Helper.
• Added simple_query() function to the database classes
• Added standard_date() function to the Date Helper.
• Added $query->free_result() to database class.
• Added $query->list_fields() function to database class
• Added $this->db->platform() function
• Added new File Helper: get_filenames()
• Added new helper: Smiley Helper
• Added support for <ul> and <ol> lists in the HTML Helper
• Added the ability to rewrite short tags on-the-fly, converting them to standard PHP statements, for those servers
that do not support short tags. This allows the cleaner syntax to be used regardless of whether it’s supported by
the server.
• Added the ability to rename or relocate the “application” folder.
• Added more thorough initialization in the upload class so that all class variables are reset.
• Added “is_numeric” to validation, which uses the native PHP is_numeric function.
• Improved the URI handler to make it more reliable when the $config[’uri_protocol’] item is set to AUTO.
• Moved most of the functions in the Controller class into the Loader class, allowing fewer reserved function
names for controllers when running under PHP 5.
• Updated the DB Result class to return an empty array when $query->result() doesn’t produce a result.
• Updated the input->cookie() and input->post() functions in Input Class to permit arrays contained cookies that
are arrays to be run through the XSS filter.
• Documented three functions from the Validation class that were missing from the user guide: set_select(),
set_radio(), and set_checkbox().
• Fixed a bug in the Email class related to SMTP Helo data.
• Fixed a bug in the word wrapping helper and function in the email class.
• Fixed a bug in the validation class.
• Fixed a bug in the typography helper that was incorrectly wrapping block level elements in paragraph tags.
• Fixed a problem in the form_prep() function that was double encoding entities.
• Fixed a bug that affects some versions of PHP when output buffering is nested.
10.5. Change Log
319
CodeIgniter Documentation, 3.0-dev
• Fixed a bug that caused CI to stop working when the PHP magic __get() or __set() functions were used within
models or controllers.
• Fixed a pagination bug that was permitting negative values in the URL.
• Fixed an oversight in which the Loader class was not allowed to be extended.
• Changed _get_config() to get_config() since the function is not a private one.
• Deprecated “init” folder. Initialization happens automatically now. Please see documentation.
• Deprecated $this->db->field_names() USE $this->db->list_fields()
• Deprecated the $config[’log_errors’] item from the config.php file. Instead, $config[’log_threshold’] can be set
to “0” to turn it off.
10.5.24 Version 1.4.1
Release Date: September 21, 2006
• Added a new feature that passes URI segments directly to your function calls as parameters. See the Controllers
page for more info.
• Added support for a function named _output(), which when used in your controllers will received the final
rendered output from the output class. More info in the Controllers page.
• Added several new functions in the URI Class to let you retrieve and manipulate URI segments that have been
re-routed using the URI Routing feature. Previously, the URI class did not permit you to access any re-routed
URI segments, but now it does.
• Added $this->output->set_header() function, which allows you to set server headers.
• Updated plugins, helpers, and language classes to allow your application folder to contain its own plugins,
helpers, and language folders. Previously they were always treated as global for your entire installation. If your
application folder contains any of these resources they will be used instead the global ones.
• Added Inflector helper.
• Added element() function in the array helper.
• Added RAND() to active record orderby() function.
• Added delete_cookie() and get_cookie() to Cookie helper, even though the input class has a cookie fetching
function.
• Added Oracle database driver (still undergoing testing so it might have some bugs).
• Added the ability to combine pseudo-variables and php variables in the template parser class.
• Added output compression option to the config file.
• Removed the is_numeric test from the db->escape() function.
• Fixed a MySQLi bug that was causing error messages not to contain proper error data.
• Fixed a bug in the email class which was causing it to ignore explicitly set alternative headers.
• Fixed a bug that was causing a PHP error when the Exceptions class was called within the get_config() function
since it was causing problems.
• Fixed an oversight in the cookie helper in which the config file cookie settings were not being honored.
• Fixed an oversight in the upload class. An item mentioned in the 1.4 changelog was missing.
• Added some code to allow email attachments to be reset when sending batches of email.
320
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Deprecated the application/scripts folder. It will continue to work for legacy users, but it is recommended that
you create your own libraries or models instead. It was originally added before CI had user libraries or models,
but it’s not needed anymore.
• Deprecated the $autoload[’core’] item from the autoload.php file. Instead, please now use: $autoload[’libraries’]
• Deprecated the following database functions: $this->db->smart_escape_str() and $this->db->fields().
10.5.25 Version 1.4.0
Release Date: September 17, 2006
• Added Hooks feature, enabling you to tap into and modify the inner workings of the framework without hacking
the core files.
• Added the ability to organize controller files into sub-folders. Kudos to Marco for suggesting this (and the next
two) feature.
• Added regular expressions support for routing rules.
• Added the ability to remap function calls within your controllers.
• Added the ability to replace core system classes with your own classes.
• Added support for % character in URL.
• Added the ability to supply full URLs using the anchor() helper function.
• Added mode parameter to file_write() helper.
• Added support for changing the port number in the Postgres driver.
• Moved the list of “allowed URI characters” out of the Router class and into the config file.
• Moved the MIME type array out of the Upload class and into its own file in the application/config/ folder.
• Updated the Upload class to allow the upload field name to be set when calling do_upload().
• Updated the Config Library to be able to load config files silently, and to be able to assign config files to their
own index (to avoid collisions if you use multiple config files).
• Updated the URI Protocol code to allow more options so that URLs will work more reliably in different environments.
• Updated the form_open() helper to allow the GET method to be used.
• Updated the MySQLi execute() function with some code to help prevent lost connection errors.
• Updated the SQLite Driver to check for object support before attempting to return results as objects. If unsupported it returns an array.
• Updated the Models loader function to allow multiple loads of the same model.
• Updated the MS SQL driver so that single quotes are escaped.
• Updated the Postgres and ODBC drivers for better compatibility.
• Removed a strtolower() call that was changing URL segments to lower case.
• Removed some references that were interfering with PHP 4.4.1 compatibility.
• Removed backticks from Postgres class since these are not needed.
• Renamed display() to _display() in the Output class to make it clear that it’s a private function.
• Deprecated the hash() function due to a naming conflict with a native PHP function with the same name. Please
use dohash() instead.
10.5. Change Log
321
CodeIgniter Documentation, 3.0-dev
• Fixed an bug that was preventing the input class from unsetting GET variables.
• Fixed a router bug that was making it too greedy when matching end segments.
• Fixed a bug that was preventing multiple discrete database calls.
• Fixed a bug in which loading a language file was producing a “file contains no data” message.
• Fixed a session bug caused by the XSS Filtering feature inadvertently changing the case of certain words.
• Fixed some missing prefixes when using the database prefix feature.
• Fixed a typo in the Calendar class (cal_november).
• Fixed a bug in the form_checkbox() helper.
• Fixed a bug that was allowing the second segment of the URI to be identical to the class name.
• Fixed an evaluation bug in the database initialization function.
• Fixed a minor bug in one of the error messages in the language class.
• Fixed a bug in the date helper timespan function.
• Fixed an undefined variable in the DB Driver class.
• Fixed a bug in which dollar signs used as binding replacement values in the DB class would be treated as RegEx
back-references.
• Fixed a bug in the set_hash() function which was preventing MD5 from being used.
• Fixed a couple bugs in the Unit Testing class.
• Fixed an incorrectly named variable in the Validation class.
• Fixed an incorrectly named variable in the URI class.
• Fixed a bug in the config class that was preventing the base URL from being called properly.
• Fixed a bug in the validation class that was not permitting callbacks if the form field was empty.
• Fixed a problem that was preventing scaffolding from working properly with MySQLi.
• Fixed some MS SQL bugs.
• Fixed some doc typos.
10.5.26 Version 1.3.3
Release Date: June 1, 2006
• Models do not connect automatically to the database as of this version. More info here.
• Updated the Sessions class to utilize the active record class when running session related queries. Previously
the queries assumed MySQL syntax.
• Updated alternator() function to re-initialize when called with no arguments, allowing multiple calls.
• Fixed a bug in the active record “having” function.
• Fixed a problem in the validation class which was making checkboxes be ignored when required.
• Fixed a bug in the word_limiter() helper function. It was cutting off the fist word.
• Fixed a bug in the xss_clean function due to a PHP bug that affects some versions of html_entity_decode.
• Fixed a validation bug that was preventing rules from being set twice in one controller.
• Fixed a calendar bug that was not letting it use dynamically loaded languages.
322
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Fixed a bug in the active record class when using WHERE clauses with LIKE
• Fixed a bug in the hash() security helper.
• Fixed some typos.
10.5.27 Version 1.3.2
Release Date: April 17, 2006
• Changed the behavior of the validation class such that if a “required” rule is NOT explicitly stated for a field
then all other tests get ignored.
• Fixed a bug in the Controller class that was causing it to look in the local “init” folder instead of the main system
one.
• Fixed a bug in the init_pagination file. The $config item was not being set correctly.
• Fixed a bug in the auto typography helper that was causing inconsistent behavior.
• Fixed a couple bugs in the Model class.
• Fixed some documentation typos and errata.
10.5.28 Version 1.3.1
Release Date: April 11, 2006
• Added a Unit Testing Library.
• Added the ability to pass objects to the insert() and update() database functions. This feature enables you to
(among other things) use your Model class variables to run queries with. See the Models page for details.
• Added the ability to pass objects to the view loading function: $this->load->view(‘my_view’, $object);
• Added getwhere function to Active Record class.
• Added count_all function to Active Record class.
• Added language file for scaffolding and fixed a scaffolding bug that occurs when there are no rows in the
specified table.
• Added $this->db->last_query(), which allows you to view your last query that was run.
• Added a new mime type to the upload class for better compatibility.
• Changed how cache files are read to prevent PHP errors if the cache file contains an XML tag, which PHP wants
to interpret as a short tag.
• Fixed a bug in a couple of the active record functions (where and orderby).
• Fixed a bug in the image library when realpath() returns false.
• Fixed a bug in the Models that was preventing libraries from being used within them.
• Fixed a bug in the “exact_length” function of the validation class.
• Fixed some typos in the user guide
10.5. Change Log
323
CodeIgniter Documentation, 3.0-dev
10.5.29 Version 1.3
Release Date: April 3, 2006
• Added support for Models.
• Redesigned the database libraries to support additional RDBMs (Postgres, MySQLi, etc.).
• Redesigned the Active Record class to enable more varied types of queries with simpler syntax, and advanced
features like JOINs.
• Added a feature to the database class that lets you run custom function calls.
• Added support for private functions in your controllers. Any controller function name that starts with an underscore will not be served by a URI request.
• Added the ability to pass your own initialization parameters to your custom core libraries when using $this>load->library()
• Added support for running standard query string URLs. These can be optionally enabled in your config file.
• Added the ability to specify a “suffix”, which will be appended to your URLs. For example, you could add .html
to your URLs, making them appear static. This feature is enabled in your config file.
• Added a new error template for use with native PHP errors.
• Added “alternator” function in the string helpers.
• Removed slashing from the input class. After much debate we decided to kill this feature.
• Change the commenting style in the scripts to the PEAR standard so that IDEs and tools like phpDocumenter
can harvest the comments.
• Added better class and function name-spacing to avoid collisions with user developed classes. All CodeIgniter
classes are now prefixed with CI_ and all controller methods are prefixed with _ci to avoid controller collisions.
A list of reserved function names can be found here.
• Redesigned how the “CI” super object is referenced, depending on whether PHP 4 or 5 is being run, since PHP
5 allows a more graceful way to manage objects that utilizes a bit less resources.
• Deprecated: $this->db->use_table() has been deprecated. Please read the Active Record page for information.
• Deprecated: $this->db->smart_escape_str() has been deprecated. Please use this instead: $this->db->escape()
• Fixed a bug in the exception handler which was preventing some PHP errors from showing up.
• Fixed a typo in the URI class. $this->total_segment() should be plural: $this->total_segments()
• Fixed some typos in the default calendar template
• Fixed some typos in the user guide
10.5.30 Version 1.2
Release Date: March 21, 2006
• Redesigned some internal aspects of the framework to resolve scoping problems that surfaced during the beta
tests. The problem was most notable when instantiating classes in your constructors, particularly if those classes
in turn did work in their constructors.
• Added a global function named get_instance() allowing the main CodeIgniter object to be accessible throughout
your own classes.
• Added new File Helper: delete_files()
324
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Added new URL Helpers: base_url(), index_page()
• Added the ability to create your own core libraries and store them in your local application directory.
• Added an overwrite option to the Upload class, enabling files to be overwritten rather than having the file name
appended.
• Added Javascript Calendar plugin.
• Added search feature to user guide. Note: This is done using Google, which at the time of this writing has not
crawled all the pages of the docs.
• Updated the parser class so that it allows tag pars within other tag pairs.
• Fixed a bug in the DB “where” function.
• Fixed a bug that was preventing custom config files to be auto-loaded.
• Fixed a bug in the mysql class bind feature that prevented question marks in the replacement data.
• Fixed some bugs in the xss_clean function
10.5.31 Version Beta 1.1
Release Date: March 10, 2006
• Added a Calendaring class.
• Added support for running multiple applications that share a common CodeIgniter backend.
• Moved the “uri protocol” variable from the index.php file into the config.php file
• Fixed a problem that was preventing certain function calls from working within constructors.
• Fixed a problem that was preventing the $this->load->library function from working in constructors.
• Fixed a bug that occurred when the session class was loaded using the auto-load routine.
• Fixed a bug that can happen with PHP versions that do not support the E_STRICT constant
• Fixed a data type error in the form_radio function (form helper)
• Fixed a bug that was preventing the xss_clean function from being called from the validation class.
• Fixed the cookie related config names, which were incorrectly specified as $conf rather than $config
• Fixed a pagination problem in the scaffolding.
• Fixed a bug in the mysql class “where” function.
• Fixed a regex problem in some code that trimmed duplicate slashes.
• Fixed a bug in the br() function in the HTML helper
• Fixed a syntax mistake in the form_dropdown function in the Form Helper.
• Removed the “style” attributes form the form helpers.
• Updated the documentation. Added “next/previous” links to each page and fixed various typos.
10.5.32 Version Beta 1.0
Release Date: February 28, 2006
First publicly released version.
10.5. Change Log
325
CodeIgniter Documentation, 3.0-dev
10.6 Open Software License (“OSL”) v 3.0
This Open Software License (the “License”) applies to any original work of authorship (the “Original Work”) whose
owner (the “Licensor”) has placed the following licensing notice adjacent to the copyright notice for the Original
Work:
Licensed under the Open Software License version 3.0
10.6.1 1) Grant of Copyright License
Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright,
to do the following:
a) to reproduce the Original Work in copies, either alone or as part of a collective work;
b) to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative
works (“Derivative Works”) based upon the Original Work;
c) to distribute or communicate copies of the Original Work and Derivative Works to the public, with the
proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be
licensed under this Open Software License;
d) to perform the Original Work publicly; and
e) to display the Original Work publicly.
10.6.2 2) Grant of Patent License
Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or
controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the
patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works.
10.6.3 3) Grant of Source Code License
The term “Source Code” means the preferred form of the Original Work for making modifications to it and all available
documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of
the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor
reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information
repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues
to distribute the Original Work.
10.6.4 4) Exclusions From License Grant
Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks
or service marks, may be used to endorse or promote products derived from this Original Work without express prior
permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor’s
trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make,
use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined
in Section 2) No license is granted to the trademarks of Licensor even if such marks are included in the Original Work.
Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License
any Original Work that Licensor otherwise would have a right to license.
326
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
10.6.5 5) External Deployment
The term “External Deployment” means the use, distribution, or communication of the Original Work or Derivative
Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether
those works are distributed or communicated to those persons or made available as an application intended for use
over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment
by You of the Original Work or a Derivative Work as a distribution under section 1(c).
10.6.6 6) Attribution Rights
You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark
notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text
identified therein as an “Attribution Notice.” You must cause the Source Code for any Derivative Works that You
create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the
Original Work.
10.6.7 7) Warranty of Provenance and Disclaimer of Warranty
Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are
owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the
Original Work is provided under this License on an “AS IS” BASIS and WITHOUT WARRANTY, either express or
implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular
purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted
by this License except under this disclaimer.
10.6.8 8) Limitation of Liability
Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall
the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising
as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation
of liability shall not apply to the extent applicable law prohibits such limitation.
10.6.9 9) Acceptance and Termination
If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance
of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work
or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of
recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section
1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring
these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended
to affect copyright exceptions and limitations (including “fair use” or “fair dealing”). This License shall terminate
immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to
honor the conditions in Section 1(c).
10.6. Open Software License (“OSL”) v 3.0
327
CodeIgniter Documentation, 3.0-dev
10.6.10 10) Termination for Patent Action
This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this
License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any
licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action
alleging patent infringement by combinations of the Original Work with other software or hardware.
10.6.11 11) Jurisdiction, Venue and Governing Law
Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor
resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflictof-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods
is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be
subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall
survive the termination of this License.
10.6.12 12) Attorneys’ Fees
In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be
entitled to recover its costs and expenses, including, without limitation, reasonable attorneys’ fees and costs incurred
in connection with such action, including any appeal of such action. This section shall survive the termination of this
License.
10.6.13 13) Miscellaneous
If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable.
10.6.14 14) Definition of “You” in This License
“You” throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights
under, and complying with all of the terms of, this License. For legal entities, “You” includes any entity that controls,
is controlled by, or is under common control with you. For purposes of this definition, “control” means (i) the power,
direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii)
ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
10.6.15 15) Right to Use
You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and
Licensor promises not to interfere with or be responsible for such uses by You.
10.6.16 16) Modification of This License
This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this
License without modification. Nothing in this License permits You to modify this License as applied to the Original
Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate
your modified version (the “Modified License”) and apply it to other original works of authorship subject to the
following conditions: (i) You may not indicate in any way that your Modified License is the “Open Software License”
or “OSL” and you may not use those names in the name of your Modified License; (ii) You must replace the notice
328
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
specified in the first paragraph above with the notice “Licensed under <insert your license name here>” or with a
notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your
original works are open source software unless your Modified License has been approved by Open Source Initiative
(OSI) and You comply with its license review and certification process.
10.7 Academic Free License (“AFL”) v 3.0
This Academic Free License (the “License”) applies to any original work of authorship (the “Original Work”) whose
owner (the “Licensor”) has placed the following licensing notice adjacent to the copyright notice for the Original
Work:
Licensed under the Academic Free License version 3.0
10.7.1 1) Grant of Copyright License
Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright,
to do the following:
a) to reproduce the Original Work in copies, either alone or as part of a collective work;
b) to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative
works (“Derivative Works”) based upon the Original Work;
c) to distribute or communicate copies of the Original Work and Derivative Works to the public, under any
license of your choice that does not contradict the terms and conditions, including Licensor’s reserved
rights and remedies, in this Academic Free License;
d) to perform the Original Work publicly; and
e) to display the Original Work publicly.
10.7.2 2) Grant of Patent License
Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or
controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the
patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works.
10.7.3 3) Grant of Source Code License
The term “Source Code” means the preferred form of the Original Work for making modifications to it and all available
documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of
the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor
reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information
repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues
to distribute the Original Work.
10.7.4 4) Exclusions From License Grant
Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks
or service marks, may be used to endorse or promote products derived from this Original Work without express prior
permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor’s
trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make,
10.7. Academic Free License (“AFL”) v 3.0
329
CodeIgniter Documentation, 3.0-dev
use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined
in Section 2) No license is granted to the trademarks of Licensor even if such marks are included in the Original Work.
Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License
any Original Work that Licensor otherwise would have a right to license.
10.7.5 5) External Deployment
The term “External Deployment” means the use, distribution, or communication of the Original Work or Derivative
Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether
those works are distributed or communicated to those persons or made available as an application intended for use
over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment
by You of the Original Work or a Derivative Work as a distribution under section 1(c).
10.7.6 6) Attribution Rights
You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark
notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text
identified therein as an “Attribution Notice.” You must cause the Source Code for any Derivative Works that You
create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the
Original Work.
10.7.7 7) Warranty of Provenance and Disclaimer of Warranty
Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are
owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the
Original Work is provided under this License on an “AS IS” BASIS and WITHOUT WARRANTY, either express or
implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular
purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted
by this License except under this disclaimer.
10.7.8 8) Limitation of Liability
Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall
the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising
as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation
of liability shall not apply to the extent applicable law prohibits such limitation.
10.7.9 9) Acceptance and Termination
If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance
of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work
or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of
recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section
1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring
these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended
to affect copyright exceptions and limitations (including “fair use” or “fair dealing”). This License shall terminate
330
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to
honor the conditions in Section 1(c).
10.7.10 10) Termination for Patent Action
This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this
License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any
licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action
alleging patent infringement by combinations of the Original Work with other software or hardware.
10.7.11 11) Jurisdiction, Venue and Governing Law
Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor
resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflictof-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods
is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be
subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall
survive the termination of this License.
10.7.12 12) Attorneys’ Fees
In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be
entitled to recover its costs and expenses, including, without limitation, reasonable attorneys’ fees and costs incurred
in connection with such action, including any appeal of such action. This section shall survive the termination of this
License.
10.7.13 13) Miscellaneous
If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable.
10.7.14 14) Definition of “You” in This License
“You” throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights
under, and complying with all of the terms of, this License. For legal entities, “You” includes any entity that controls,
is controlled by, or is under common control with you. For purposes of this definition, “control” means (i) the power,
direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii)
ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
10.7.15 15) Right to Use
You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and
Licensor promises not to interfere with or be responsible for such uses by You.
10.7. Academic Free License (“AFL”) v 3.0
331
CodeIgniter Documentation, 3.0-dev
10.7.16 16) Modification of This License
This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this
License without modification. Nothing in this License permits You to modify this License as applied to the Original
Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate
your modified version (the “Modified License”) and apply it to other original works of authorship subject to the
following conditions: (i) You may not indicate in any way that your Modified License is the “Academic Free License”
or “AFL” and you may not use those names in the name of your Modified License; (ii) You must replace the notice
specified in the first paragraph above with the notice “Licensed under <insert your license name here>” or with a
notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your
original works are open source software unless your Modified License has been approved by Open Source Initiative
(OSI) and You comply with its license review and certification process.
10.8 CodeIgniter Overview
The following pages describe the broad concepts behind CodeIgniter:
10.8.1 Getting Started With CodeIgniter
Any software application requires some effort to learn. We’ve done our best to minimize the learning curve while
making the process as enjoyable as possible.
The first step is to install CodeIgniter, then read all the topics in the Introduction section of the Table of Contents.
Next, read each of the General Topics pages in order. Each topic builds on the previous one, and includes code
examples that you are encouraged to try.
Once you understand the basics you’ll be ready to explore the Class Reference and Helper Reference pages to learn
to utilize the native libraries and helper files.
Feel free to take advantage of our Community Forums if you have questions or problems, and our Wiki to see code
examples posted by other users.
10.8.2 CodeIgniter at a Glance
CodeIgniter is an Application Framework
CodeIgniter is a toolkit for people who build web applications 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 Free
CodeIgniter is licensed under an Apache/BSD-style open source license so you can use it however you please. For
more information please read the license agreement.
332
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
CodeIgniter is Light Weight
Truly light weight. The core system requires only a few very small libraries. This is in stark contrast to many
frameworks that require significantly more resources. Additional libraries are loaded dynamically upon request, based
on your needs for a given process, so the base system is very lean and quite fast.
CodeIgniter is Fast
Really fast. We challenge you to find a framework that has better performance than CodeIgniter.
CodeIgniter Uses M-V-C
CodeIgniter uses the Model-View-Controller approach, which allows great separation between logic and presentation.
This is particularly good for projects in which designers are working with your template files, as the code these files
contain will be minimized. We describe MVC in more detail on its own page.
CodeIgniter Generates Clean URLs
The URLs generated by CodeIgniter are clean and search-engine friendly. Rather than using the standard “query
string” approach to URLs that is synonymous with dynamic systems, CodeIgniter uses a segment-based approach:
example.com/news/article/345
Note: By default the index.php file is included in the URL but it can be removed using a simple .htaccess file.
CodeIgniter Packs a Punch
CodeIgniter comes with full-range of libraries that enable the most commonly needed web development tasks, like
accessing a database, sending email, validating form data, maintaining sessions, manipulating images, working with
XML-RPC data and much more.
CodeIgniter is Extensible
The system can be easily extended through the use of your own libraries, helpers, or through class extensions or system
hooks.
CodeIgniter Does Not Require a Template Engine
Although CodeIgniter does come with a simple template parser that can be optionally used, it does not force you to
use one. Template engines simply can not match the performance of native PHP, and the syntax that must be learned
to use a template engine is usually only marginally easier than learning the basics of PHP. Consider this block of PHP
code:
<ul>
<?php foreach ($addressbook as $name):?>
<li><?=$name?></li>
<?php endforeach; ?>
</ul>
Contrast this with the pseudo-code used by a template engine:
10.8. CodeIgniter Overview
333
CodeIgniter Documentation, 3.0-dev
<ul>
{foreach from=$addressbook item="name"}
<li>{$name}</li>
{/foreach}
</ul>
Yes, the template engine example is a bit cleaner, but it comes at the price of performance, as the pseudo-code must
be converted back into PHP to run. Since one of our goals is maximum performance, we opted to not require the use
of a template engine.
CodeIgniter is Thoroughly Documented
Programmers love to code and hate to write documentation. We’re no different, of course, but since documentation is
as important as the code itself, we are committed to doing it. Our source code is extremely clean and well commented
as well.
CodeIgniter has a Friendly Community of Users
Our growing community of users can be seen actively participating in our Community Forums.
10.8.3 CodeIgniter Features
Features in and of themselves are a very poor way to judge an application since they tell you nothing about the user
experience, or how intuitively or intelligently it is designed. Features don’t reveal anything about the quality of the
code, or the performance, or the attention to detail, or security practices. The only way to really judge an app is to try
it and get to know the code. Installing CodeIgniter is child’s play so we encourage you to do just that. In the mean
time here’s a list of CodeIgniter’s main features.
• Model-View-Controller Based System
• Extremely Light Weight
• Full Featured database classes with support for several platforms.
• Query Builder Database Support
• Form and Data Validation
• Security and XSS Filtering
• Session Management
• Email Sending Class. Supports Attachments, HTML/Text email, multiple protocols (sendmail, SMTP, and Mail)
and more.
• Image Manipulation Library (cropping, resizing, rotating, etc.). Supports GD, ImageMagick, and NetPBM
• File Uploading Class
• FTP Class
• Localization
• Pagination
• Data Encryption
• Benchmarking
• Full Page Caching
334
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Error Logging
• Application Profiling
• Calendaring Class
• User Agent Class
• Zip Encoding Class
• Template Engine Class
• Trackback Class
• XML-RPC Library
• Unit Testing Class
• Search-engine Friendly URLs
• Flexible URI Routing
• Support for Hooks and Class Extensions
• Large library of “helper” functions
10.8.4 Application Flow Chart
The following graphic illustrates how data flows throughout the system:
1. The index.php serves as the front controller, initializing the base resources needed to run CodeIgniter.
2. The Router examines the HTTP request to determine what should be done with it.
3. If a cache file exists, it is sent directly to the browser, bypassing the normal system execution.
4. Security. Before the application controller is loaded, the HTTP request and any user submitted data is filtered
for security.
5. The Controller loads the model, core libraries, helpers, and any other resources needed to process the specific
request.
6. The finalized View is rendered then sent to the web browser to be seen. If caching is enabled, the view is cached
first so that on subsequent requests it can be served.
10.8.5 Model-View-Controller
CodeIgniter is based on the Model-View-Controller development pattern. MVC is a software approach that separates
application logic from presentation. In practice, it permits your web pages to contain minimal scripting since the
presentation is separate from the PHP scripting.
• The Model represents your data structures. Typically your model classes will contain functions that help you
retrieve, insert, and update information in your database.
• The View is the information that is being presented to a user. A View will normally be a web page, but in
CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other
type of “page”.
• The Controller serves as an intermediary between the Model, the View, and any other resources needed to
process the HTTP request and generate a web page.
10.8. CodeIgniter Overview
335
CodeIgniter Documentation, 3.0-dev
CodeIgniter has a fairly loose approach to MVC since Models are not required. If you don’t need the added separation, or find that maintaining models requires more complexity than you want, you can ignore them and build your
application minimally using Controllers and Views. CodeIgniter also enables you to incorporate your own existing
scripts, or even develop core libraries for the system, enabling you to work in a way that makes the most sense to you.
10.8.6 Design and Architectural Goals
Our goal for CodeIgniter is maximum performance, capability, and flexibility in the smallest, lightest possible package.
To meet this goal we are committed to benchmarking, re-factoring, and simplifying at every step of the development
process, rejecting anything that doesn’t further the stated objective.
From a technical and architectural standpoint, CodeIgniter was created with the following objectives:
• Dynamic Instantiation. In CodeIgniter, components are loaded and routines executed only when requested,
rather than globally. No assumptions are made by the system regarding what may be needed beyond the minimal
core resources, so the system is very light-weight by default. The events, as triggered by the HTTP request, and
the controllers and views you design will determine what is invoked.
• Loose Coupling. Coupling is the degree to which components of a system rely on each other. The less components depend on each other the more reusable and flexible the system becomes. Our goal was a very loosely
coupled system.
• Component Singularity. Singularity is the degree to which components have a narrowly focused purpose. In
CodeIgniter, each class and its functions are highly autonomous in order to allow maximum usefulness.
CodeIgniter is a dynamically instantiated, loosely coupled system with high component singularity. It strives for
simplicity, flexibility, and high performance in a small footprint package.
10.9 Server Requirements
• PHP version 5.2.4 or newer.
• A Database is required for most web application programming. Currently supported databases are: - MySQL
(5.1+) via the mysql (deprecated), mysqli and pdo drivers - Oracle via the oci8 and pdo drivers - PostgreSQL
via the postgre and pdo drivers - MS SQL via the mssql, sqlsrv (version 2005 and above only) and pdo drivers
- SQLite via the sqlite (version 2), sqlite3 (version 3) and pdo drivers - CUBRID via the cubrid and pdo drivers
- Interbase/Firebird via the ibase and pdo drivers - ODBC via the odbc and pdo drivers (you should know that
ODBC is actually an abstraction layer)
10.10 Welcome to CodeIgniter
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.
10.10.1 Who is CodeIgniter For?
CodeIgniter is right for you if:
• You want a framework with a small footprint.
336
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• You need exceptional performance.
• You need broad compatibility with standard hosting accounts that run a variety of PHP versions and configurations.
• You want a framework that requires nearly zero configuration.
• You want a framework that does not require you to use the command line.
• You want a framework that does not require you to adhere to restrictive coding rules.
• You are not interested in large-scale monolithic libraries like PEAR.
• You do not want to be forced to learn a templating language (although a template parser is optionally available
if you desire one).
• You eschew complexity, favoring simple solutions.
• You need clear, thorough documentation.
10.11 Installation Instructions
CodeIgniter is installed in four steps:
1. Unzip the package.
2. Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root.
3. Open the application/config/config.php file with a text editor and set your base URL. If you intend to use encryption or sessions, set your encryption key.
4. If you intend to use a database, open the application/config/database.php file with a text editor and set your
database settings.
If you wish to increase security by hiding the location of your CodeIgniter files you can rename the system and
application folders to something more private. If you do rename them, you must open your main index.php file and
set the $system_path and $application_folder variables at the top of the file with the new name you’ve chosen.
For the best security, both the system and any application folders should be placed above web root so that they are not
directly accessible via a browser. By default, .htaccess files are included in each folder to help prevent direct access,
but it is best to remove them from public access entirely in case the web server configuration changes or doesn’t abide
by the .htaccess.
If you would like to keep your views public it is also possible to move the views folder out of your application folder.
After moving them, open your main index.php file and set the $system_path, $application_folder and $view_folder
variables, preferably with a full path, e.g. ‘/www/MyUser/system’.
One additional measure to take in production environments is to disable PHP error reporting and any other
development-only functionality. In CodeIgniter, this can be done by setting the ENVIRONMENT constant, which
is more fully described on the security page.
That’s it!
If you’re new to CodeIgniter, please read the Getting Started section of the User Guide to begin learning how to build
dynamic PHP applications. Enjoy!
10.11.1 Downloading CodeIgniter
• CodeIgniter v3.0.0 (Current version)
10.11. Installation Instructions
337
CodeIgniter Documentation, 3.0-dev
• CodeIgniter v2.1.4 (MD5 Checksum: e74a296c1d412a855c025b9cd468a513)
• CodeIgniter v2.1.3 (MD5 Checksum: 781d06be06eaa36f10759ef82c8594d5)
• CodeIgniter v2.1.2 (MD5 Checksum: c7a2980dff2774c97bd38bfbf450d8d5)
• CodeIgniter v2.1.1 (MD5 Checksum: c4aa5f188f4ff16f919607b46a16c76c)
• CodeIgniter v2.1.0 (MD5 Checksum: 8cb676b0f831114935d7dd1ae2e0d490)
• CodeIgniter v2.0.3 (MD5 Checksum: 910475d50daf088bdd949c3d35b444d9)
• CodeIgniter v2.0.2 (MD5 Checksum: e75bab8cf27d2fb2483c5bb61b85a524)
• CodeIgniter v2.0.1 (MD5 Checksum: 675aa95896bfb16467436c0484f15f1f)
• CodeIgniter v2.0.0 (MD5 Checksum: bd657863de45dbb397f3b3dbc4f13abb)
• CodeIgniter v1.7.3 (MD5 Checksum: 16f50e7df4f44c1defe18355131049e9)
• CodeIgniter v1.7.2 (MD5 Checksum: ff2f4d1b3ab921f91e006f38b3ae6540)
• CodeIgniter v1.7.1 (MD5 Checksum: deca9709cf21b26dc0e4ec040b37e866)
• CodeIgniter v1.7.0 (MD5 Checksum: 28037f2071f940d8756864460d949045)
• CodeIgniter v1.6.3 (MD5 Checksum: 5ffab52b39b235ed6bd08ee5dd64d2f6)
• CodeIgniter v1.6.2 (MD5 Checksum: 0922830f96dfd40874b39ad018a49206)
• CodeIgniter v1.6.1 (MD5 Checksum: cc3f0b566e3654d351fa067aeee9bced)
• CodeIgniter v1.6.0 (MD5 Checksum: 89efabb8c1d57bb51071e6a20bb5590d)
• CodeIgniter v1.5.4 (MD5 Checksum: 0d6cc66b01d5ddecde483b3d5f51e4f8)
• CodeIgniter v1.5.3 (MD5 Checksum: f44dd21d34a2842bd052879ca5de6630)
• CodeIgniter v1.5.2 (MD5 Checksum: 78e7106b271f75af48e626f6e923c1aa)
• CodeIgniter v1.5.1 (MD5 Checksum: 9dfd0dbed4f283a42a817e1e88f97481)
• CodeIgniter v1.5.0 (MD5 Checksum: 116b805eae4b7e78ddd43a8aee733632)
• CodeIgniter v1.4.1 (MD5 Checksum: 470005a83772e9d2e99dec2b4058e584)
• CodeIgniter v1.4.0 (MD5 Checksum: 43ca6ff3447d6b5681f98a328b386338)
• CodeIgniter v1.3.3 (MD5 Checksum: 55692ba4b55b53b58e4514e310288981)
• CodeIgniter v1.3.2 (MD5 Checksum: 7dace6e1d6245b569943e8df952c7637)
• CodeIgniter v1.3.1 (MD5 Checksum: f6c6f00830c60d7f98b948269ee81069)
• CodeIgniter v1.3 (MD5 Checksum: 03b2f796df6af808ecff3a18b6000477)
• CodeIgniter v1.2 (MD5 Checksum: f9289814fabe102bc35beb791d0c0f62)
• CodeIgniter v1.1 (MD5 Checksum: bf4cabb6a3ea3122a974270b8044befb)
• CodeIgniter v1.0 (MD5 Checksum: 427ca4255e2bdaacee976de1aa143ea0)
GitHub
Git is a distributed version control system.
Public Git access is available at GitHub. Please note that while every effort is made to keep this code base functional,
we cannot guarantee the functionality of code taken from the develop branch.
338
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Beginning with version 2.0.3, stable versions are also available via GitHub Releases.
10.11.2 Troubleshooting
If you find that no matter what you put in your URL only your default page is loading, it might be that your server
does not support the PATH_INFO variable needed to serve search-engine friendly URLs. As a first step, open your
application/config/config.php file and look for the URI Protocol information. It will recommend that you try a couple
alternate settings. If it still doesn’t work after you’ve tried this you’ll need to force CodeIgniter to add a question mark
to your URLs. To do this open your application/config/config.php file and change this:
$config[’index_page’] = "index.php";
To this:
$config[’index_page’] = "index.php?";
10.11.3 Upgrading From Beta 1.0 to Final 1.2
To upgrade to Version 1.2 please replace the following directories with the new versions:
: If you have any custom developed files in these folders please make copies of them first.
• drivers
• helpers
• init
• language
• libraries
• plugins
• scaffolding
Please also replace your local copy of the user guide with the new version.
10.11.4 Upgrading from 1.2 to 1.3
: The instructions on this page assume you are running version 1.2. If you have not upgraded to that version please
do so first.
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace the following directories in your “system” folder with the new versions:
: If you have any custom developed files in these folders please make copies of them first.
• application/models/ (new for 1.3)
• codeigniter (new for 1.3)
10.11. Installation Instructions
339
CodeIgniter Documentation, 3.0-dev
• drivers
• helpers
• init
• language
• libraries
• plugins
• scaffolding
Step 2: Update your error files
Version 1.3 contains two new error templates located in application/errors, and for naming consistency the other error
templates have been renamed.
If you have not customized any of the error templates simply replace this folder:
• application/errors/
If you have customized your error templates, rename them as follows:
• 404.php = error_404.php
• error.php = error_general.php
• error_db.php (new)
• error_php.php (new)
Step 3: Update your index.php file
Please open your main index.php file (located at your root). At the very bottom of the file, change this:
require_once BASEPATH.’libraries/Front_controller’.EXT;
To this:
require_once BASEPATH.’codeigniter/CodeIgniter’.EXT;
Step 4: Update your config.php file
Open your application/config/config.php file and add these new items:
/*
|-----------------------------------------------| URL suffix
|-----------------------------------------------|
| This option allows you to add a suffix to all URLs.
| For example, if a URL is this:
|
| example.com/index.php/products/view/shoes
|
| You can optionally add a suffix, like ".html",
| making the page appear to be of a certain type:
|
340
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
| example.com/index.php/products/view/shoes.html
|
*/
$config[’url_suffix’] = "";
/*
|-----------------------------------------------| Enable Query Strings
|-----------------------------------------------|
| By default CodeIgniter uses search-engine and
| human-friendly segment based URLs:
|
| example.com/who/what/where/
|
| You can optionally enable standard query string
| based URLs:
|
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The two other items let you set the query string "words"
| that will invoke your controllers and functions:
| example.com/index.php?c=controller&m=function
|
*/
$config[’enable_query_strings’] = FALSE;
$config[’controller_trigger’] = ’c’;
$config[’function_trigger’] = ’m’;
Step 5: Update your database.php file
Open your application/config/database.php file and add these new items:
$db[’default’][’dbprefix’] = "";
$db[’default’][’active_r’] = TRUE;
Step 6: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.5 Upgrading from 1.3 to 1.3.1
: The instructions on this page assume you are running version 1.3. If you have not upgraded to that version please
do so first.
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace the following directories in your “system” folder with the new versions:
10.11. Installation Instructions
341
CodeIgniter Documentation, 3.0-dev
: If you have any custom developed files in these folders please make copies of them first.
• drivers
• init/init_unit_test.php (new for 1.3.1)
• language/
• libraries
• scaffolding
Step 2: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.6 Upgrading from 1.3.1 to 1.3.2
: The instructions on this page assume you are running version 1.3.1. If you have not upgraded to that version please
do so first.
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace the following directories in your “system” folder with the new versions:
: If you have any custom developed files in these folders please make copies of them first.
• drivers
• init
• libraries
Step 2: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.7 Upgrading from 1.3.2 to 1.3.3
: The instructions on this page assume you are running version 1.3.2. If you have not upgraded to that version please
do so first.
Before performing an update you should take your site offline by replacing the index.php file with a static one.
342
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Step 1: Update your CodeIgniter files
Replace the following directories in your “system” folder with the new versions:
: If you have any custom developed files in these folders please make copies of them first.
• codeigniter
• drivers
• helpers
• init
• libraries
Step 2: Update your Models
If you are NOT using CodeIgniter’s Models feature disregard this step.
As of version 1.3.3, CodeIgniter does not connect automatically to your database when a model is loaded. This allows
you greater flexibility in determining which databases you would like used with your models. If your application is
not connecting to your database prior to a model being loaded you will have to update your code. There are several
options for connecting, as described here.
Step 3: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.8 Upgrading from 1.3.3 to 1.4.0
: The instructions on this page assume you are running version 1.3.3. If you have not upgraded to that version please
do so first.
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace the following directories in your “system” folder with the new versions:
: If you have any custom developed files in these folders please make copies of them first.
• application/config/hooks.php
• application/config/mimes.php
• codeigniter
• drivers
• helpers
• init
• language
10.11. Installation Instructions
343
CodeIgniter Documentation, 3.0-dev
• libraries
• scaffolding
Step 2: Update your config.php file
Open your application/config/config.php file and add these new items:
/*
|-------------------------------------------------------------------------| Enable/Disable System Hooks
|-------------------------------------------------------------------------|
| If you would like to use the "hooks" feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config[’enable_hooks’] = FALSE;
/*
|-------------------------------------------------------------------------| Allowed URL Characters
|-------------------------------------------------------------------------|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_|
| Leave blank to allow all characters -- but only if you are insane.
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config[’permitted_uri_chars’] = ’a-z 0-9~%.:_-’;
Step 3: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.9 Upgrading from 1.4.0 to 1.4.1
: The instructions on this page assume you are running version 1.4.0. If you have not upgraded to that version please
do so first.
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace the following directories in your “system” folder with the new versions:
344
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
: If you have any custom developed files in these folders please make copies of them first.
• codeigniter
• drivers
• helpers
• libraries
Step 2: Update your config.php file
Open your application/config/config.php file and add this new item:
/*
|-------------------------------------------------------------------------| Output Compression
|-------------------------------------------------------------------------|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not "echo" any values with compression enabled.
|
*/
$config[’compress_output’] = FALSE;
Step 3: Rename an Autoload Item
Open the following file: application/config/autoload.php
Find this array item:
$autoload[’core’] = array();
And rename it to this:
$autoload[’libraries’] = array();
This change was made to improve clarity since some users were not sure that their own libraries could be auto-loaded.
Step 4: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.10 Upgrading from 1.4.1 to 1.5.0
: The instructions on this page assume you are running version 1.4.1. If you have not upgraded to that version please
10.11. Installation Instructions
345
CodeIgniter Documentation, 3.0-dev
do so first.
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace these files and directories in your “system” folder with the new versions:
• application/config/user_agents.php (new file for 1.5)
• application/config/smileys.php (new file for 1.5)
• codeigniter/
• database/ (new folder for 1.5. Replaces the “drivers” folder)
• helpers/
• language/
• libraries/
• scaffolding/
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Update your database.php file
Open your application/config/database.php file and add these new items:
$db[’default’][’cache_on’] = FALSE;
$db[’default’][’cachedir’] = ’’;
Step 3: Update your config.php file
Open your application/config/config.php file and ADD these new items:
/*
|-------------------------------------------------------------------------| Class Extension Prefix
|-------------------------------------------------------------------------|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config[’subclass_prefix’] = ’MY_’;
/*
|-------------------------------------------------------------------------| Rewrite PHP Short Tags
|-------------------------------------------------------------------------|
| If your PHP installation does not have short tag support enabled CI
346
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
*/
$config[’rewrite_short_tags’] = FALSE;
In that same file REMOVE this item:
/*
|-------------------------------------------------------------------------| Enable/Disable Error Logging
|-------------------------------------------------------------------------|
| If you would like errors or debug messages logged set this variable to
| TRUE (boolean). Note: You must set the file permissions on the "logs" folder
| such that it is writable.
|
*/
$config[’log_errors’] = FALSE;
Error logging is now disabled simply by setting the threshold to zero.
Step 4: Update your main index.php file
If you are running a stock index.php file simply replace your version with the new one.
If your index.php file has internal modifications, please add your modifications to the new file and use it.
Step 5: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.11 Upgrading from 1.5.0 to 1.5.2
: The instructions on this page assume you are running version 1.5.0 or 1.5.1. If you have not upgraded to that version
please do so first.
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace these files and directories in your “system” folder with the new versions:
• system/helpers/download_helper.php
• system/helpers/form_helper.php
• system/libraries/Table.php
• system/libraries/User_agent.php
• system/libraries/Exceptions.php
• system/libraries/Input.php
• system/libraries/Router.php
10.11. Installation Instructions
347
CodeIgniter Documentation, 3.0-dev
• system/libraries/Loader.php
• system/libraries/Image_lib.php
• system/language/english/unit_test_lang.php
• system/database/DB_active_rec.php
• system/database/drivers/mysqli/mysqli_driver.php
• codeigniter/
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.12 Upgrading from 1.5.2 to 1.5.3
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace these files and directories in your “system” folder with the new versions:
• system/database/drivers
• system/helpers
• system/libraries/Input.php
• system/libraries/Loader.php
• system/libraries/Profiler.php
• system/libraries/Table.php
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.13 Upgrading from 1.5.3 to 1.5.4
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace these files and directories in your “system” folder with the new versions:
• application/config/mimes.php
• system/codeigniter
348
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• system/database
• system/helpers
• system/libraries
• system/plugins
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Add charset to your config.php
Add the following to application/config/config.php
/*
|-------------------------------------------------------------------------| Default Character Set
|-------------------------------------------------------------------------|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
*/
$config[’charset’] = "UTF-8";
Step 3: Autoloading language files
If you want to autoload any language files, add this line to application/config/autoload.php
$autoload[’language’] = array();
Step 4: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.14 Upgrading from 1.5.4 to 1.6.0
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace these files and directories in your “system” folder with the new versions:
• system/codeigniter
• system/database
• system/helpers
• system/libraries
• system/plugins
• system/language
10.11. Installation Instructions
349
CodeIgniter Documentation, 3.0-dev
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Add time_to_update to your config.php
Add the following to application/config/config.php with the other session configuration options
$config[’sess_time_to_update’]
= 300;
Step 3: Add $autoload[’model’]
Add the following to application/config/autoload.php
/*
| ------------------------------------------------------------------| Auto-load Model files
| ------------------------------------------------------------------| Prototype:
|
| $autoload[’model’] = array(’my_model’);
|
*/
$autoload[’model’] = array();
Step 4: Add to your database.php
Make the following changes to your application/config/database.php file:
Add the following variable above the database configuration options, with $active_group
$active_record = TRUE;
Remove the following from your database configuration options
$db[’default’][’active_r’] = TRUE;
Add the following to your database configuration options
$db[’default’][’char_set’] = "utf8";
$db[’default’][’dbcollat’] = "utf8_general_ci";
Step 5: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.15 Upgrading from 1.6.0 to 1.6.1
Before performing an update you should take your site offline by replacing the index.php file with a static one.
350
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Step 1: Update your CodeIgniter files
Replace these files and directories in your “system” folder with the new versions:
• system/codeigniter
• system/database
• system/helpers
• system/language
• system/libraries
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.16 Upgrading from 1.6.1 to 1.6.2
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace these files and directories in your “system” folder with the new versions:
• system/codeigniter
• system/database
• system/helpers
• system/language
• system/libraries
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Encryption Key
If you are using sessions, open up application/config/config.php and verify you’ve set an encryption key.
Step 3: Constants File
Copy /application/config/constants.php to your installation, and modify if necessary.
Step 4: Mimes File
Replace /application/config/mimes.php with the dowloaded version. If you’ve added custom mime types, you’ll need
to re-add them.
10.11. Installation Instructions
351
CodeIgniter Documentation, 3.0-dev
Step 5: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.17 Upgrading from 1.6.2 to 1.6.3
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace these files and directories in your “system” folder with the new versions:
• system/codeigniter
• system/database
• system/helpers
• system/language
• system/libraries
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.18 Upgrading from 1.6.3 to 1.7.0
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace these files and directories in your “system” folder with the new versions:
• system/codeigniter
• system/database
• system/helpers
• system/language
• system/libraries
: If you have any custom developed files in these folders please make copies of them first.
352
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Step 2: Update your Session Table
If you are using the Session class in your application, AND if you are storing session data to a database, you must
add a new column named user_data to your session table. Here is an example of what this column might look like for
MySQL:
user_data text NOT NULL
To add this column you will run a query similar to this:
ALTER TABLE ‘ci_sessions‘ ADD ‘user_data‘ text NOT NULL
You’ll find more information regarding the new Session functionality in the Session class page.
Step 3: Update your Validation Syntax
This is an optional, but recommended step, for people currently using the Validation class. CI 1.7 introduces a new
Form Validation class, which deprecates the old Validation library. We have left the old one in place so that existing
applications that use it will not break, but you are encouraged to migrate to the new version as soon as possible. Please
read the user guide carefully as the new library works a little differently, and has several new features.
Step 4: Update your user guide
Please replace your local copy of the user guide with the new version, including the image files.
10.11.19 Upgrading from 1.7.0 to 1.7.1
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace these files and directories in your “system” folder with the new versions:
• system/codeigniter
• system/database
• system/helpers
• system/language
• system/libraries
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Update your user guide
Please replace your local copy of the user guide with the new version, including the image files.
10.11.20 Upgrading from 1.7.1 to 1.7.2
Before performing an update you should take your site offline by replacing the index.php file with a static one.
10.11. Installation Instructions
353
CodeIgniter Documentation, 3.0-dev
Step 1: Update your CodeIgniter files
Replace these files and directories in your “system” folder with the new versions:
• system/codeigniter
• system/database
• system/helpers
• system/language
• system/libraries
• index.php
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Remove header() from 404 error template
If you are using header() in your 404 error template, such as the case with the default error_404.php template shown
below, remove that line of code.
<?php header("HTTP/1.1 404 Not Found"); ?>
404 status headers are now properly handled in the show_404() method itself.
Step 3: Confirm your system_path
In your updated index.php file, confirm that the $system_path variable is set to your application’s system folder.
Step 4: Update your user guide
Please replace your local copy of the user guide with the new version, including the image files.
10.11.21 Upgrading from 1.7.2 to 2.0.0
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Update Instructions
Step 1: Update your CodeIgniter files
Replace all files and directories in your “system” folder except your application folder.
: If you have any custom developed files in these folders please make copies of them first.
354
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Step 2: Adjust get_dir_file_info() where necessary
Version 2.0.0 brings a non-backwards compatible change to get_dir_file_info() in the File Helper. Non-backwards
compatible changes are extremely rare in CodeIgniter, but this one we feel was warranted due to how easy it was to
create serious server performance issues. If you need recursiveness where you are using this helper function, change
such instances, setting the second parameter, $top_level_only to FALSE:
get_dir_file_info(’/path/to/directory’, FALSE);
Step 3: Convert your Plugins to Helpers
2.0.0 gets rid of the “Plugin” system as their functionality was identical to Helpers, but non-extensible. You will
need to rename your plugin files from filename_pi.php to filename_helper.php, move them to your helpers folder, and
change all instances of:
$this->load->plugin(’foo’);
to
$this->load->helper(’foo’);
Step 4: Update stored encrypted data
: If your application does not use the Encryption library, does not store Encrypted data permanently, or is on an
environment that does not support Mcrypt, you may skip this step.
The Encryption library has had a number of improvements, some for encryption strength and some for performance,
that has an unavoidable consequence of making it no longer possible to decode encrypted data produced by the original
version of this library. To help with the transition, a new method has been added, encode_from_legacy() that will
decode the data with the original algorithm and return a re-encoded string using the improved methods. This will
enable you to easily replace stale encrypted data with fresh in your applications, either on the fly or en masse.
Please read how to use this method in the Encryption library documentation.
Step 5: Remove loading calls for the compatibility helper.
The compatibility helper has been removed from the CodeIgniter core. All methods in it should be natively available
in supported PHP versions.
Step 6: Update Class extension
All core classes are now prefixed with CI_. Update Models and Controllers to extend CI_Model and CI_Controller,
respectively.
Step 7: Update Parent Constructor calls
All native CodeIgniter classes now use the PHP 5 __construct() convention. Please update extended libraries to call
parent::__construct().
10.11. Installation Instructions
355
CodeIgniter Documentation, 3.0-dev
Step 8: Move any core extensions to application/core
Any extensions to core classes (e.g. MY_Controller.php) in your application/libraries folder must be moved to the
new application/core folder.
Step 9: Update your user guide
Please replace your local copy of the user guide with the new version, including the image files.
Update Notes
Please refer to the 2.0.0 Change Log for full details, but here are some of the larger changes that are more likely to
impact your code:
• CodeIgniter now requires PHP 5.2.4.
• Scaffolding has been removed.
• The CAPTCHA plugin in now a helper.
• The JavaScript calendar plugin was removed.
• The system/cache and system/logs directories are now in the application directory.
• The Validation class has been removed. Please see the Form Validation library
• “default” is now a reserved name.
• The xss_clean() function has moved to the Security Class.
• do_xss_clean() now returns FALSE if the uploaded file fails XSS checks.
• The Session Class requires now the use of an encryption key set in the config file.
• The following deprecated Active Record functions have been removed: orwhere, orlike, groupby,
orhaving, orderby, getwhere.
• _drop_database() and _create_database() functions have been removed from the db utility drivers.
• The dohash() function of the Security helper has been renamed to do_hash() for naming consistency.
The config folder
The following files have been changed:
• config.php
• database.php
• mimes.php
• routes.php
• user_agents.php
The following files have been added:
• foreign_chars.php
• profiler.php
356
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
10.11.22 Upgrading from 2.0.0 to 2.0.1
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace all files and directories in your “system” folder and replace your index.php file. If any modifications were
made to your index.php they will need to be made fresh in this new one.
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Replace config/mimes.php
This config file has been updated to contain more mime types, please copy it to application/config/mimes.php.
Step 3: Check for forms posting to default controller
The default behavior for form_open() when called with no parameters used to be to post to the default controller, but it
will now just leave an empty action=”” meaning the form will submit to the current URL. If submitting to the default
controller was the expected behavior it will need to be changed from:
echo form_open(); //<form action="" method="post" accept-charset="utf-8">
to use either a / or base_url():
echo form_open(’/’); //<form action="http://example.com/index.php/" method="post" accept-charset="utf
echo form_open(base_url()); //<form action="http://example.com/" method="post" accept-charset="utf-8"
10.11.23 Upgrading from 2.0.1 to 2.0.2
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace all files and directories in your “system” folder and replace your index.php file. If any modifications were
made to your index.php they will need to be made fresh in this new one.
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Remove loading calls for the Security Library
Security has been moved to the core and is now always loaded automatically. Make sure you remove any loading calls
as they will result in PHP errors.
10.11. Installation Instructions
357
CodeIgniter Documentation, 3.0-dev
Step 3: Move MY_Security
If you are overriding or extending the Security library, you will need to move it to application/core.
csrf_token_name and csrf_hash have changed to protected class properties. Please use security->get_csrf_hash() and
security->get_csrf_token_name() to access those values.
10.11.24 Upgrading from 2.0.2 to 2.0.3
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace all files and directories in your “system” folder and replace your index.php file. If any modifications were
made to your index.php they will need to be made fresh in this new one.
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Update your main index.php file
If you are running a stock index.php file simply replace your version with the new one.
If your index.php file has internal modifications, please add your modifications to the new file and use it.
Step 3: Replace config/user_agents.php
This config file has been updated to contain more user agent types, please copy it to application/config/user_agents.php.
Step 4: Change references of the EXT constant to ”.php”
: The EXT Constant has been marked as deprecated, but has not been removed from the application. You are
encouraged to make the changes sooner rather than later.
Step 5: Remove APPPATH.’third_party’ from autoload.php
Open application/config/autoload.php, and look for the following:
$autoload[’packages’] = array(APPPATH.’third_party’);
If you have not chosen to load any additional packages, that line can be changed to:
$autoload[’packages’] = array();
Which should provide for nominal performance gains if not autoloading packages.
358
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Update Sessions Database Tables
If you are using database sessions with the CI Session Library, please update your ci_sessions database table as follows:
CREATE INDEX last_activity_idx ON ci_sessions(last_activity);
ALTER TABLE ci_sessions MODIFY user_agent VARCHAR(120);
10.11.25 Upgrading from 2.0.3 to 2.1.0
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace all files and directories in your “system” folder.
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Replace config/user_agents.php
This config file has been updated to contain more user agent types, please copy it to _application/config/user_agents.php*.
Step 3: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.26 Upgrading from 2.1.0 to 2.1.1
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace all files and directories in your “system” folder.
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Replace config/mimes.php
This config file has been updated to contain more user mime-types, please copy it to _application/config/mimes.php*.
Step 3: Update your IP address tables
This upgrade adds support for IPv6 IP addresses. In order to store them, you need to enlarge your ip_address columns
to 45 characters. For example, CodeIgniter’s session table will need to change
ALTER TABLE ci_sessions CHANGE ip_address ip_address varchar(45) default ’0’ NOT NULL
10.11. Installation Instructions
359
CodeIgniter Documentation, 3.0-dev
10.11.27 Upgrading from 2.1.1 to 2.1.2
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace all files and directories in your “system” folder.
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.28 Upgrading from 2.1.2 to 2.1.3
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace all files and directories in your “system” folder.
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Update your user guide
Please also replace your local copy of the user guide with the new version.
10.11.29 Upgrading from 2.1.3 to 2.1.4
Before performing an update you should take your site offline by replacing the index.php file with a static one.
Step 1: Update your CodeIgniter files
Replace all files and directories in your “system” folder.
: If you have any custom developed files in these folders please make copies of them first.
10.11.30 Upgrading from 2.1.4 to 3.0.0
: These upgrade notes are for a version that is yet to be released.
Before performing an update you should take your site offline by replacing the index.php file with a static one.
360
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Step 1: Update your CodeIgniter files
Replace all files and directories in your “system” folder and replace your index.php file. If any modifications were
made to your index.php they will need to be made fresh in this new one.
: If you have any custom developed files in these folders please make copies of them first.
Step 2: Update your classes file names
Starting with CodeIgniter 3.0, 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.
For example, if you have the following library file:
application/libraries/mylibrary.php
... then you’ll have to rename it to:
application/libraries/Mylibrary.php
The same goes for driver libraries and extensions and/or overrides of CodeIgniter’s own libraries and core classes.
application/libraries/MY_email.php application/core/MY_log.php
The above files should respectively be renamed to the following:
application/libraries/MY_Email.php application/core/MY_Log.php
Controllers:
application/controllers/welcome.php -> application/controllers/Welcome.php
Models:
application/models/misc_model.php -> application/models/Misc_model.php
Please note that this DOES NOT affect directories, configuration files, views, helpers, hooks and anything else - it is
only applied to classes.
You must now follow just one simple rule - class names in Ucfirst and everything else in lowercase.
Step 3: Replace config/mimes.php
This config file has been updated to contain more user mime-types, please copy it to _application/config/mimes.php*.
Step 4: Remove $autoload[’core’] from your config/autoload.php
Use of the $autoload[’core’] config array has been deprecated as of CodeIgniter 1.4.1 and is now removed.
Move any entries that you might have listed there to $autoload[’libraries’] instead.
Step 5: Move your Log class overrides or extensions
The Log Class is considered as a “core” class and is now located in the system/core/ directory. Therefore, in order for
your Log class overrides or extensions to work, you need to move them to application/core/:
application/libraries/Log.php -> application/core/Log.php
application/libraries/MY_Log.php -> application/core/MY_Log.php
10.11. Installation Instructions
361
CodeIgniter Documentation, 3.0-dev
Step 6: Convert your Session usage from library to driver
When you load (or autoload) the Session library, you must now load it as a driver instead of a library. This means
calling $this->load->driver(’session’) instead of $this->load->library(’session’) and/or
listing ‘session’ in $autoload[’drivers’] instead of $autoload[’libraries’].
With the change from a single Session Library to the new Session Driver, two new config items have been added:
• $config[’sess_driver’] selects which driver to initially load. Options are:
– ‘cookie’ (the default) for classic CodeIgniter cookie-based sessions
– ‘native’ for native PHP Session support
– the name of a custom driver you have provided (see Session Driver for more info)
• $config[’sess_valid_drivers’] provides an array of additional custom drivers to make available for
loading
As the new Session Driver library loads the classic Cookie driver by default and always makes ‘cookie’ and ‘native’
available as valid drivers, neither of these configuration items are required. However, it is recommended that you add
them for clarity and ease of configuration in the future.
If you have written a Session extension, you must move it into a ‘Session’ sub-directory of ‘libraries’, following the
standard for Drivers. Also beware that some functions which are not part of the external Session API have moved into
the drivers, so your extension may have to be broken down into separate library and driver class extensions.
Step 7: Update your config/database.php
Due to 3.0.0’s renaming of Active Record to Query Builder, inside your config/database.php, you will need to rename
the $active_record variable to $query_builder
$active_group = ’default’;
// $active_record = TRUE;
$query_builder = TRUE;
Step 8: Replace your error templates
In CodeIgniter 3.0, the error templates are now considered as views and have been moved to the _application/views/errors* directory.
Furthermore, we’ve added support for CLI error templates in plain-text format that unlike HTML, is suitable for the
command line. This of course requires another level of separation.
It is safe to move your old templates from _application/errors* to _application/views/errors/html*, but you’ll have to
copy the new _application/views/errors/cli* directory from the CodeIgniter archive.
Step 9: Update your config/routes.php containing (:any)
Historically, CodeIgniter has always provided the :any wildcard in routing, with the intention of providing a way to
match any character within an URI segment.
However, the :any wildcard is actually just an alias for a regular expression and used to be executed in that manner as
.+. This is considered a bug, as it also matches the / (forward slash) character, which is the URI segment delimiter and
that was never the intention. In CodeIgniter 3, the :any wildcard will now represent [^/]+, so that it will not match a
forward slash.
362
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
There are certainly many developers that have utilized this bug as an actual feature. If you’re one of them and want to
match a forward slash, please use the .+ regular expression:
(.+)
(:any)
// matches ANYTHING
// matches any character, except for ’/’
Step 10: Many functions now return NULL instead of FALSE on missing items
Many methods and functions now return NULL instead of FALSE when the required items don’t exist:
• Config Class
– config->item()
– config->slash_item()
• Input Class
– input->get()
– input->post()
– input->get_post()
– input->cookie()
– input->server()
– input->input_stream()
– input->get_request_header()
• Session Class
– session->userdata()
– session->flashdata()
• URI Class
– uri->segment()
– uri->rsegment()
• Array Helper
– element()
– elements()
Step 11: Update usage of Input Class’s get_post() method
Previously, the Input Class method get_post() was searching first in POST data, then in GET data. This method
has been modified so that it searches in GET then in POST, as its name suggests.
A method has been added, post_get(), which searches in POST then in GET, as get_post() was doing before.
Step 12: Update usage of Directory Helper’s directory_map() function
In the resulting array, directories now end with a trailing directory separator (i.e. a slash, usually).
10.11. Installation Instructions
363
CodeIgniter Documentation, 3.0-dev
Step 13: Update usage of Database Forge’s drop_table() method
Up until now, drop_table() added an IF EXISTS clause by default or it didn’t work at all with some drivers. In
CodeIgniter 3.0, the IF EXISTS condition is no longer added by default and has an optional second parameter that
allows that instead and is set to FALSE by default.
If your application relies on IF EXISTS, you’ll have to change its usage.
// Now produces just DROP TABLE ‘table_name‘
$this->dbforge->drop_table(’table_name’);
// Produces DROP TABLE IF EXISTS ‘table_name‘
$this->dbforge->drop_table(’table_name’, TRUE);
: The given example uses MySQL-specific syntax, but it should work across all drivers with the exception of ODBC.
Step 14: Change usage of Email library with multiple emails
The Email Library will automatically clear the set parameters after successfully sending emails. To override this
behaviour, pass FALSE as the first parameter in the send() method:
if ($this->email->send(FALSE))
{
// Parameters won’t be cleared
}
Step 15: Update your Form_validation language lines
Two improvements have been made to the Form Validation Library‘s language files and error messages format:
• Language Library line keys now must be prefixed with form_validation_ in order to avoid collisions:
// Old
$lang[’rule’] = ...
// New
$lang[’form_validation_rule’] = ...
• The error messages format has been changed to use named parameters, to allow more flexibility than what
sprintf() offers:
// Old
’The %s field does not match the %s field.’
// New
’The {field} field does not match the {param} field.’
: The old formatting still works, but the non-prefixed line keys are DEPRECATED and scheduled for removal in
CodeIgniter 3.1+. Therefore you’re encouraged to update its usage sooner rather than later.
Step 16: Remove usage of (previously) deprecated functionalities
In addition to the $autoload[’core’] configuration setting, there’s a number of other functionalities that have
been removed in CodeIgniter 3.0.0:
364
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
The SHA1 library
The previously deprecated SHA1 library has been removed, alter your code to use PHP’s native sha1() function to
generate a SHA1 hash.
Additionally, the sha1() method in the Encryption Library has been removed.
The EXT constant
Usage of the EXT constant has been deprecated since dropping support for PHP 4. There’s no longer a need to maintain
different filename extensions and in this new CodeIgniter version, the EXT constant has been removed. Use just ‘.php’
instead.
Smiley helper js_insert_smiley()
Smiley Helper function js_insert_smiley() has been deprecated since CodeIgniter 1.7.2 and is now removed.
You’ll need to switch to smiley_js() instead.
Security helper do_hash()
Security Helper function do_hash() is now just an alias for PHP’s native hash() function. It is deprecated and
scheduled for removal in CodeIgniter 3.1+.
: This function is still available, but you’re strongly encouraged to remove its usage sooner rather than later.
File helper read_file()
File Helper function read_file() is now just an alias for PHP’s native file_get_contents() function. It is
deprecated and scheduled for removal in CodeIgniter 3.1+.
: This function is still available, but you’re strongly encouraged to remove its usage sooner rather than later.
String helper repeater()
String Helper function repeater() is now just an alias for PHP’s native str_repeat() function. It is deprecated
and scheduled for removal in CodeIgniter 3.1+.
: This function is still available, but you’re strongly encouraged to remove its usage sooner rather than later.
String helper trim_slashes()
String Helper function trim_slashes() is now just an alias for PHP’s native trim() function (with a slash
passed as its second argument). It is deprecated and scheduled for removal in CodeIgniter 3.1+.
: This function is still available, but you’re strongly encouraged to remove its usage sooner rather than later.
10.11. Installation Instructions
365
CodeIgniter Documentation, 3.0-dev
Email helper functions
Email Helper only has two functions
• valid_email()
• send_email()
Both of them are now aliases for PHP’s native filter_var() and mail() functions, respectively. Therefore the
Email Helper altogether is being deprecated and is scheduled for removal in CodeIgniter 3.1+.
: These functions are still available, but you’re strongly encouraged to remove their usage sooner rather than later.
Date helper standard_date()
Date Helper function standard_date() is being deprecated due to the availability of native PHP constants, which
when combined with date() provide the same functionality. Furthermore, they have the exact same names as the
ones supported by standard_date(). Here are examples of how to replace its usage:
// Old way
standard_date(); // defaults to standard_date(’DATE_RFC822’, now());
// Replacement
date(DATE_RFC822, now());
// Old way
standard_date(’DATE_ATOM’, $time);
// Replacement
date(DATE_ATOM, $time);
: This function is still available, but you’re strongly encouraged to remove its usage sooner rather than later as it is
scheduled for removal in CodeIgniter 3.1+.
Pagination library ‘anchor_class’ setting
The Pagination Library now supports adding pretty much any HTML attribute to your anchors via the ‘attributes’
configuration setting. This includes passing the ‘class’ attribute and using the separate ‘anchor_class’ setting no
longer makes sense. As a result of that, the ‘anchor_class’ setting is now deprecated and scheduled for removal in
CodeIgniter 3.1+.
: This setting is still available, but you’re strongly encouraged to remove its usage sooner rather than later.
String helper random_string() types ‘unique’ and ‘encrypt’
When using the String Helper function random_string(), you should no longer pass the unique and encrypt
randomization types. They are only aliases for md5 and sha1 respectively and are now deprecated and scheduled for
removal in CodeIgniter 3.1+.
: These options are still available, but you’re strongly encouraged to remove their usage sooner rather than later.
366
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
URL helper url_title() separators ‘dash’ and ‘underscore’
When using the URL Helper function url_title(), you should no longer pass dash or underscore as the word
separator. This function will now accept any character and you should just pass the chosen character directly, so you
should write ‘-‘ instead of ‘dash’ and ‘_’ instead of ‘underscore’.
dash and underscore now act as aliases and are deprecated and scheduled for removal in CodeIgniter 3.1+.
: These options are still available, but you’re strongly encouraged to remove their usage sooner rather than later.
Database Forge method add_column() with an AFTER clause
If you have used the third parameter for Database Forge method add_column() to add a field for an AFTER
clause, then you should change its usage.
That third parameter has been deprecated and scheduled for removal in CodeIgniter 3.1+.
You should now put AFTER clause field names in the field definition array instead:
// Old usage:
$field = array(
’new_field’ => array(’type’ => ’TEXT’)
);
$this->dbforge->add_column(’table_name’, $field, ’another_field’);
// New usage:
$field = array(
’new_field’ => array(’type’ => ’TEXT’, ’after’ => ’another_field’)
);
$this->dbforge->add_column(’table_name’, $field);
: The parameter is still available, but you’re strongly encouraged to remove its usage sooner rather than later.
: This is for MySQL and CUBRID databases only! Other drivers don’t support this clause and will silently ignore it.
URI Routing methods fetch_directory(), fetch_class(), fetch_method()
With properties CI_Router::$directory, CI_Router::$class and CI_Router::$method being public and their respective fetch_*() no longer doing anything else to just return the properties - it doesn’t make sense
to keep them.
Those are all internal, undocumented methods, but we’ve opted to deprecate them for now in order to maintain
backwards-compatibility just in case. If some of you have utilized them, then you can now just access the properties instead:
$this->router->directory;
$this->router->class;
$this->router->method;
: Those methods are still available, but you’re strongly encouraged to remove their usage sooner rather than later.
10.11. Installation Instructions
367
CodeIgniter Documentation, 3.0-dev
Input library method is_cli_request()
Calls to the CI_Input::is_cli_request() method are necessary at many places in the CodeIgniter internals
and this is often before the Input Library is loaded. Because of that, it is being replaced by a common function named
is_cli() and this method is now just an alias.
The new function is both available at all times for you to use and shorter to type.
// Old
$this->input->is_cli_request();
// New
is_cli();
CI_Input::is_cli_request() is now now deprecated and scheduled for removal in CodeIgniter 3.1+.
: This method is still available, but you’re strongly encouraged to remove its usage sooner rather than later.
10.11.31 Upgrading From Beta 1.0 to Beta 1.1
To upgrade to Beta 1.1 please perform the following steps:
Step 1: Replace your index file
Replace your main index.php file with the new index.php file. Note: If you have renamed your “system” folder you
will need to edit this info in the new file.
Step 2: Relocate your config folder
This version of CodeIgniter now permits multiple sets of “applications” to all share a common set of backend files. In
order to enable each application to have its own configuration values, the config directory must now reside inside of
your application folder, so please move it there.
Step 3: Replace directories
Replace the following directories with the new versions:
• drivers
• helpers
• init
• libraries
• scaffolding
Step 4: Add the calendar language file
There is a new language file corresponding to the new calendaring class which must be added to your language folder.
Add the following item to your version: language/english/calendar_lang.php
368
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Step 5: Edit your config file
The original application/config/config.php file has a typo in it Open the file and look for the items related to cookies:
$conf[’cookie_prefix’]
$conf[’cookie_domain’]
$conf[’cookie_path’]
= "";
= "";
= "/";
Change the array name from $conf to $config, like this:
$config[’cookie_prefix’]
$config[’cookie_domain’]
$config[’cookie_path’] = "/";
= "";
= "";
Lastly, add the following new item to the config file (and edit the option if needed):
/*
|-----------------------------------------------| URI PROTOCOL
|-----------------------------------------------|
| This item determines which server global
| should be used to retrieve the URI string. The
| default setting of "auto" works for most servers.
| If your links do not seem to work, try one of
| the other delicious flavors:
|
| ’auto’
Default - auto detects
| ’path_info’
Uses the PATH_INFO
| ’query_string’
Uses the QUERY_STRING
*/
$config[’uri_protocol’] = "auto";
10.11.32 Upgrading From a Previous Version
Please read the upgrade notes corresponding to the version you are upgrading from.
• Upgrading from 2.1.4 to 3.0.0
• Upgrading from 2.1.3 to 2.1.4
• Upgrading from 2.1.2 to 2.1.3
• Upgrading from 2.1.1 to 2.1.2
• Upgrading from 2.1.0 to 2.1.1
• Upgrading from 2.0.3 to 2.1.0
• Upgrading from 2.0.2 to 2.0.3
• Upgrading from 2.0.1 to 2.0.2
• Upgrading from 2.0 to 2.0.1
• Upgrading from 1.7.2 to 2.0
• Upgrading from 1.7.1 to 1.7.2
• Upgrading from 1.7.0 to 1.7.1
10.11. Installation Instructions
369
CodeIgniter Documentation, 3.0-dev
• Upgrading from 1.6.3 to 1.7.0
• Upgrading from 1.6.2 to 1.6.3
• Upgrading from 1.6.1 to 1.6.2
• Upgrading from 1.6.0 to 1.6.1
• Upgrading from 1.5.4 to 1.6.0
• Upgrading from 1.5.3 to 1.5.4
• Upgrading from 1.5.2 to 1.5.3
• Upgrading from 1.5.0 or 1.5.1 to 1.5.2
• Upgrading from 1.4.1 to 1.5.0
• Upgrading from 1.4.0 to 1.4.1
• Upgrading from 1.3.3 to 1.4.0
• Upgrading from 1.3.2 to 1.3.3
• Upgrading from 1.3.1 to 1.3.2
• Upgrading from 1.3 to 1.3.1
• Upgrading from 1.2 to 1.3
• Upgrading from 1.1 to 1.2
• Upgrading from Beta 1.0 to Beta 1.1
10.12 General Topics
10.12.1 CodeIgniter URLs
By default, URLs in CodeIgniter are designed to be search-engine and human friendly. Rather than using the standard
“query string” approach to URLs that is synonymous with dynamic systems, CodeIgniter uses a segment-based
approach:
example.com/news/article/my_article
: Query string URLs can be optionally enabled, as described below.
URI Segments
The segments in the URL, in following with the Model-View-Controller approach, usually represent:
example.com/class/function/ID
1. The first segment represents the controller class that should be invoked.
2. The second segment represents the class function, or method, that should be called.
3. The third, and any additional segments, represent the ID and any variables that will be passed to the controller.
The URI Library and the URL Helper contain functions that make it easy to work with your URI data. In addition,
your URLs can be remapped using the URI Routing feature for more flexibility.
370
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Removing the index.php file
By default, the index.php file will be included in your URLs:
example.com/index.php/news/article/my_article
If your Apache server has mod_rewrite enabled, you can easily remove this file by using a .htaccess file with some
simple rules. Here is an example of such a file, using the “negative” method in which everything is redirected except
the specified items:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
In the above example, any HTTP request other than those for existing directories and existing files is treated as a
request for your index.php file.
: These specific rules might not work for all server configurations.
: Make sure to also exclude from the above rule any assets that you might need to be accessible from the outside
world.
Adding a URL Suffix
In your config/config.php file you can specify a suffix that will be added to all URLs generated by CodeIgniter. For
example, if a URL is this:
example.com/index.php/products/view/shoes
You can optionally add a suffix, like .html, making the page appear to be of a certain type:
example.com/index.php/products/view/shoes.html
Enabling Query Strings
In some cases you might prefer to use query strings URLs:
index.php?c=products&m=view&id=345
CodeIgniter optionally supports this capability, which can be enabled in your application/config.php file. If you open
your config file you’ll see these items:
$config[’enable_query_strings’] = FALSE;
$config[’controller_trigger’] = ’c’;
$config[’function_trigger’] = ’m’;
If you change “enable_query_strings” to TRUE this feature will become active. Your controllers and functions will
then be accessible using the “trigger” words you’ve set to invoke your controllers and methods:
index.php?c=controller&m=method
: If you are using query strings you will have to build your own URLs, rather than utilizing the URL helpers (and
other helpers that generate URLs, like some of the form helpers) as these are designed to work with segment based
URLs.
10.12. General Topics
371
CodeIgniter Documentation, 3.0-dev
10.12.2 Controllers
Controllers are the heart of your application, as they determine how HTTP requests should be handled.
Page Contents
• Controllers
– What is a Controller?
– Let’s try it: Hello World!
– Methods
– Passing URI Segments to your methods
– Defining a Default Controller
– Remapping Method Calls
– Processing Output
– Private methods
– Organizing Your Controllers into Sub-directories
– Class Constructors
– Reserved method names
– That’s it!
What is a Controller?
A Controller is simply a class file that is named in a way that can be associated with a URI.
Consider this URI:
example.com/index.php/blog/
In the above example, CodeIgniter would attempt to find a controller named Blog.php and load it.
When a controller’s name matches the first segment of a URI, it will be loaded.
Let’s try it: Hello World!
Let’s create a simple controller so you can see it in action. Using your text editor, create a file called Blog.php, and
put the following code in it:
<?php
class Blog extends CI_Controller {
public function index()
{
echo ’Hello World!’;
}
}
Then save the file to your application/controllers/ directory.
: The file must be called ‘Blog.php’, with a capital ‘B’.
Now visit the your site using a URL similar to this:
example.com/index.php/blog/
If you did it right, you should see:
372
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Hello World!
: Class names must start with an uppercase letter.
This is valid:
<?php
class Blog extends CI_Controller {
}
This is not valid:
<?php
class blog extends CI_Controller {
}
Also, always make sure your controller extends the parent controller class so that it can inherit all its methods.
Methods
In the above example the method name is index(). The “index” method is always loaded by default if the second
segment of the URI is empty. Another way to show your “Hello World” message would be this:
example.com/index.php/blog/index/
The second segment of the URI determines which method in the controller gets called.
Let’s try it. Add a new method to your controller:
<?php
class Blog extends CI_Controller {
public function index()
{
echo ’Hello World!’;
}
public function comments()
{
echo ’Look at this!’;
}
}
Now load the following URL to see the comment method:
example.com/index.php/blog/comments/
You should see your new message.
Passing URI Segments to your methods
If your URI contains more then two segments they will be passed to your method as parameters.
For example, let’s say you have a URI like this:
10.12. General Topics
373
CodeIgniter Documentation, 3.0-dev
example.com/index.php/products/shoes/sandals/123
Your method will be passed URI segments 3 and 4 (“sandals” and “123”):
<?php
class Products extends CI_Controller {
public function shoes($sandals, $id)
{
echo $sandals;
echo $id;
}
}
: If you are using the URI Routing feature, the segments passed to your method will be the re-routed ones.
Defining a Default Controller
CodeIgniter can be told to load a default controller when a URI is not present, as will be the case when only your
site root URL is requested. To specify a default controller, open your application/config/routes.php file and set this
variable:
$route[’default_controller’] = ’Blog’;
Where Blog is the name of the controller class you want used. If you now load your main index.php file without
specifying any URI segments you’ll see your Hello World message by default.
Remapping Method Calls
As noted above, the second segment of the URI typically determines which method in the controller gets called.
CodeIgniter permits you to override this behavior through the use of the _remap() method:
public function _remap()
{
// Some code here...
}
: If your controller contains a method named _remap(), it will always get called regardless of what your URI contains.
It overrides the normal behavior in which the URI determines which method is called, allowing you to define your
own method routing rules.
The overridden method call (typically the second segment of the URI) will be passed as a parameter to the _remap()
method:
public function _remap($method)
{
if ($method === ’some_method’)
{
$this->$method();
}
else
{
$this->default_method();
}
}
374
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Any extra segments after the method name are passed into _remap() as an optional second parameter. This array
can be used in combination with PHP’s call_user_func_array() to emulate CodeIgniter’s default behavior.
Example:
public function _remap($method, $params = array())
{
$method = ’process_’.$method;
if (method_exists($this, $method))
{
return call_user_func_array(array($this, $method), $params);
}
show_404();
}
Processing Output
CodeIgniter has an output class that takes care of sending your final rendered data to the web browser automatically.
More information on this can be found in the Views and Output Class pages. In some cases, however, you might want
to post-process the finalized data in some way and send it to the browser yourself. CodeIgniter permits you to add a
method named _output() to your controller that will receive the finalized output data.
: If your controller contains a method named _output(), it will always be called by the output class instead of
echoing the finalized data directly. The first parameter of the method will contain the finalized output.
Here is an example:
public function _output($output)
{
echo $output;
}
: Please note that your _output() method will receive the data in its finalized state. Benchmark and memory
usage data will be rendered, cache files written (if you have caching enabled), and headers will be sent (if you use
that feature) before it is handed off to the _output() method. To have your controller’s output cached properly, its
_output() method can use:
if ($this->output->cache_expiration > 0)
{
$this->output->_write_cache($output);
}
If you are using this feature the page execution timer and memory usage stats might not be perfectly accurate since
they will not take into account any further processing you do. For an alternate way to control output before any of the
final processing is done, please see the available methods in the Output Library.
Private methods
In some cases you may want certain methods hidden from public access. In order to achieve this, simply declare the
method as being private or protected and it will not be served via a URL request. For example, if you were to have a
method like this:
private function _utility()
{
10.12. General Topics
375
CodeIgniter Documentation, 3.0-dev
// some code
}
Trying to access it via the URL, like this, will not work:
example.com/index.php/blog/_utility/
: Prefixing method names with an underscore will also prevent them from being called. This is a legacy feature that
is left for backwards-compatibility.
Organizing Your Controllers into Sub-directories
If you are building a large application you might find it convenient to organize your controllers into sub-directories.
CodeIgniter permits you to do this.
Simply create folders within your application/controllers/ directory and place your controller classes within them.
: When using this feature the first segment of your URI must specify the folder. For example, let’s say you have a
controller located here:
application/controllers/products/Shoes.php
To call the above controller your URI will look something like this:
example.com/index.php/products/shoes/show/123
Each of your sub-directories may contain a default controller which will be called if the URL contains only the subfolder. Simply name your default controller as specified in your application/config/routes.php file.
CodeIgniter also permits you to remap your URIs using its URI Routing feature.
Class Constructors
If you intend to use a constructor in any of your Controllers, you MUST place the following line of code in it:
parent::__construct();
The reason this line is necessary is because your local constructor will be overriding the one in the parent controller
class so we need to manually call it.
Example:
<?php
class Blog extends CI_Controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
}
}
Constructors are useful if you need to set some default values, or run a default process when your class is instantiated.
Constructors can’t return a value, but they can do some default work.
376
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Reserved method names
Since your controller classes will extend the main application controller you must be careful not to name your methods
identically to the ones used by that class, otherwise your local functions will override them. See Reserved Names for
a full list.
:
You should also never have a method named identically to its class name. If you do, and there is no
__construct() method in the same class, then your e.g. Index::index() method will be executed as a
class constructor! This is a PHP4 backwards-compatibility feature.
That’s it!
That, in a nutshell, is all there is to know about controllers.
10.12.3 Reserved Names
In order to help out, CodeIgniter uses a series of function, method, class and variable names in its operation. Because
of this, some names cannot be used by a developer. Following is a list of reserved names that cannot be used.
Controller names
Since your controller classes will extend the main application controller you must be careful not to name your methods
identically to the ones used by that class, otherwise your local methods will override them. The following is a list of
reserved names. Do not name your controller any of these:
• Controller
• CI_Base
• _ci_initialize
• Default
• index
Functions
• is_php()
• is_really_writable()
• load_class()
• is_loaded()
• get_config()
• config_item()
• show_error()
• show_404()
• log_message()
• set_status_header()
• get_mimes()
10.12. General Topics
377
CodeIgniter Documentation, 3.0-dev
• html_escape()
• remove_invisible_characters()
• is_https()
• function_usable()
• get_instance()
• _exception_handler()
• _stringify_attributes()
Variables
• $config
• $db
• $lang
Constants
• ENVIRONMENT
• FCPATH
• SELF
• BASEPATH
• APPPATH
• VIEWPATH
• CI_VERSION
• FILE_READ_MODE
• FILE_WRITE_MODE
• DIR_READ_MODE
• DIR_WRITE_MODE
• FOPEN_READ
• FOPEN_READ_WRITE
• FOPEN_WRITE_CREATE_DESTRUCTIVE
• FOPEN_READ_WRITE_CREATE_DESTRUCTIVE
• FOPEN_WRITE_CREATE
• FOPEN_READ_WRITE_CREATE
• FOPEN_WRITE_CREATE_STRICT
• FOPEN_READ_WRITE_CREATE_STRICT
• EXIT_SUCCESS
• EXIT_ERROR
• EXIT_CONFIG
378
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• EXIT_UNKNOWN_FILE
• EXIT_UNKNOWN_CLASS
• EXIT_UNKNOWN_METHOD
• EXIT_USER_INPUT
• EXIT_DATABASE
• EXIT__AUTO_MIN
• EXIT__AUTO_MAX
10.12.4 Views
A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be
embedded within other views (within other views, etc., etc.) if you need this type of hierarchy.
Views are never called directly, they must be loaded by a controller. Remember that in an MVC framework, the
Controller acts as the traffic cop, so it is responsible for fetching a particular view. If you have not read the Controllers
page you should do so before continuing.
Using the example controller you created in the controller page, let’s add a view to it.
Creating a View
Using your text editor, create a file called blogview.php, and put this in it:
<html>
<head>
<title>My Blog</title>
</head>
<body>
<h1>Welcome to my Blog!</h1>
</body>
</html>
Then save the file in your application/views/ directory.
Loading a View
To load a particular view file you will use the following method:
$this->load->view(’name’);
Where name is the name of your view file.
: The .php file extension does not need to be specified unless you use something other than .php.
Now, open the controller file you made earlier called Blog.php, and replace the echo statement with the view loading
method:
<?php
class Blog extends CI_Controller {
public function index()
{
10.12. General Topics
379
CodeIgniter Documentation, 3.0-dev
$this->load->view(’blogview’);
}
}
If you visit your site using the URL you did earlier you should see your new view. The URL was similar to this:
example.com/index.php/blog/
Loading multiple views
CodeIgniter will intelligently handle multiple calls to $this->load->view() from within a controller. If more
than one call happens they will be appended together. For example, you may wish to have a header view, a menu view,
a content view, and a footer view. That might look something like this:
<?php
class Page extends CI_Controller {
public function index()
{
$data[’page_title’] = ’Your title’;
$this->load->view(’header’);
$this->load->view(’menu’);
$this->load->view(’content’, $data);
$this->load->view(’footer’);
}
}
In the example above, we are using “dynamically added data”, which you will see below.
Storing Views within Sub-directories
Your view files can also be stored within sub-directories if you prefer that type of organization. When doing so you
will need to include the directory name loading the view. Example:
$this->load->view(’directory_name/file_name’);
Adding Dynamic Data to the View
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view
loading method. Here is an example using an array:
$data = array(
’title’ => ’My Title’,
’heading’ => ’My Heading’,
’message’ => ’My Message’
);
$this->load->view(’blogview’, $data);
And here’s an example using an object:
$data = new Someclass();
$this->load->view(’blogview’, $data);
380
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
: If you use an object, the class variables will be turned into array elements.
Let’s try it with your controller file. Open it add this code:
<?php
class Blog extends CI_Controller {
public function index()
{
$data[’title’] = "My Real Title";
$data[’heading’] = "My Real Heading";
$this->load->view(’blogview’, $data);
}
}
Now open your view file and change the text to variables that correspond to the array keys in your data:
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
</body>
</html>
Then load the page at the URL you’ve been using and you should see the variables replaced.
Creating Loops
The data array you pass to your view files is not limited to simple variables. You can pass multi dimensional arrays,
which can be looped to generate multiple rows. For example, if you pull data from your database it will typically be
in the form of a multi-dimensional array.
Here’s a simple example. Add this to your controller:
<?php
class Blog extends CI_Controller {
public function index()
{
$data[’todo_list’] = array(’Clean House’, ’Call Mom’, ’Run Errands’);
$data[’title’] = "My Real Title";
$data[’heading’] = "My Real Heading";
$this->load->view(’blogview’, $data);
}
}
Now open your view file and create a loop:
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
10.12. General Topics
381
CodeIgniter Documentation, 3.0-dev
<h1><?php echo $heading;?></h1>
<h3>My Todo List</h3>
<ul>
<?php foreach ($todo_list as $item):?>
<li><?php echo $item;?></li>
<?php endforeach;?>
</ul>
</body>
</html>
: You’ll notice that in the example above we are using PHP’s alternative syntax. If you are not familiar with it you
can read about it here.
Returning views as data
There is a third optional parameter lets you change the behavior of the method so that it returns data as a string rather
than sending it to your browser. This can be useful if you want to process the data in some way. If you set the parameter
to TRUE (boolean) it will return data. The default behavior is false, which sends it to your browser. Remember to
assign it to a variable if you want the data returned:
$string = $this->load->view(’myfile’, ’’, TRUE);
10.12.5 Models
Models are optionally available for those who want to use a more traditional MVC approach.
Page Contents
• Models
– What is a Model?
– Anatomy of a Model
– Loading a Model
– Auto-loading Models
– Connecting to your Database
What is a Model?
Models are PHP classes that are designed to work with information in your database. For example, let’s say you use
CodeIgniter to manage a blog. You might have a model class that contains functions to insert, update, and retrieve
your blog data. Here is an example of what such a model class might look like:
class Blog_model extends CI_Model {
public $title;
public $content;
public $date;
382
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
public function get_last_ten_entries()
{
$query = $this->db->get(’entries’, 10);
return $query->result();
}
public function insert_entry()
{
$this->title
= $_POST[’title’]; // please read the below note
$this->content = $_POST[’content’];
$this->date
= time();
$this->db->insert(’entries’, $this);
}
public function update_entry()
{
$this->title
= $_POST[’title’];
$this->content = $_POST[’content’];
$this->date
= time();
$this->db->update(’entries’, $this, array(’id’ => $_POST[’id’]));
}
}
: The methods in the above example use the Query Builder database methods.
: For the sake of simplicity in this example we’re using $_POST directly. This is generally bad practice, and a more
common approach would be to use the Input Library $this->input->post(’title’).
Anatomy of a Model
Model classes are stored in your application/models/ directory. They can be nested within sub-directories if you want
this type of organization.
The basic prototype for a model class is this:
class Model_name extends CI_Model {
public function __construct()
{
parent::__construct();
}
}
Where Model_name is the name of your class. Class names must have the first letter capitalized with the rest of the
name lowercase. Make sure your class extends the base Model class.
10.12. General Topics
383
CodeIgniter Documentation, 3.0-dev
The file name must match the class name. For example, if this is your class:
class User_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
}
Your file will be this:
application/models/User_model.php
Loading a Model
Your models will typically be loaded and called from within your controller methods. To load a model you will use
the following method:
$this->load->model(’model_name’);
If your model is located in a sub-directory, include the relative path from your models directory. For example, if you
have a model located at application/models/blog/Queries.php you’ll load it using:
$this->load->model(’blog/queries’);
Once loaded, you will access your model methods using an object with the same name as your class:
$this->load->model(’model_name’);
$this->model_name->method();
If you would like your model assigned to a different object name you can specify it via the second parameter of the
loading method:
$this->load->model(’model_name’, ’foobar’);
$this->foobar->method();
Here is an example of a controller, that loads a model, then serves a view:
class Blog_controller extends CI_Controller {
public function blog()
{
$this->load->model(’blog’);
$data[’query’] = $this->Blog->get_last_ten_entries();
$this->load->view(’blog’, $data);
}
}
Auto-loading Models
If you find that you need a particular model globally throughout your application, you can tell CodeIgniter to autoload it during system initialization. This is done by opening the application/config/autoload.php file and adding the
384
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
model to the autoload array.
Connecting to your Database
When a model is loaded it does NOT connect automatically to your database. The following options for connecting
are available to you:
• You can connect using the standard database methods described here, either from within your Controller class
or your Model class.
• You can tell the model loading method to auto-connect by passing TRUE (boolean) via the third parameter, and
connectivity settings, as defined in your database config file will be used:
$this->load->model(’model_name’, ’’, TRUE);
• You can manually pass database connectivity settings via the third parameter:
$config[’hostname’]
$config[’username’]
$config[’password’]
$config[’database’]
$config[’dbdriver’]
$config[’dbprefix’]
$config[’pconnect’]
$config[’db_debug’]
=
=
=
=
=
=
=
=
’localhost’;
’myusername’;
’mypassword’;
’mydatabase’;
’mysqli’;
’’;
FALSE;
TRUE;
$this->load->model(’model_name’, ’’, $config);
10.12.6 Helper Functions
Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular
category. There are URL Helpers, that assist in creating links, there are Form Helpers that help you create form
elements, Text Helpers perform various text formatting routines, Cookie Helpers set and read cookies, File Helpers
help you deal with files, etc.
Unlike most other systems in CodeIgniter, Helpers are not written in an Object Oriented format. They are simple,
procedural functions. Each helper function performs one specific task, with no dependence on other functions.
CodeIgniter does not load Helper Files by default, so the first step in using a Helper is to load it. Once loaded, it
becomes globally available in your controller and views.
Helpers are typically stored in your system/helpers, or application/helpers directory. CodeIgniter will look first in
your application/helpers directory. If the directory does not exist or the specified helper is not located there CI will
instead look in your global system/helpers/ directory.
Loading a Helper
Loading a helper file is quite simple using the following method:
$this->load->helper(’name’);
Where name is the file name of the helper, without the .php file extension or the “helper” part.
For example, to load the URL Helper file, which is named url_helper.php, you would do this:
$this->load->helper(’url’);
10.12. General Topics
385
CodeIgniter Documentation, 3.0-dev
A helper can be loaded anywhere within your controller methods (or even within your View files, although that’s not
a good practice), as long as you load it before you use it. You can load your helpers in your controller constructor so
that they become available automatically in any function, or you can load a helper in a specific function that needs it.
: The Helper loading method above does not return a value, so don’t try to assign it to a variable. Just use it as shown.
Loading Multiple Helpers
If you need to load more than one helper you can specify them in an array, like this:
$this->load->helper(
array(’helper1’, ’helper2’, ’helper3’)
);
Auto-loading Helpers
If you find that you need a particular helper globally throughout your application, you can tell CodeIgniter to autoload it during system initialization. This is done by opening the application/config/autoload.php file and adding the
helper to the autoload array.
Using a Helper
Once you’ve loaded the Helper File containing the function you intend to use, you’ll call it the way you would a
standard PHP function.
For example, to create a link using the anchor() function in one of your view files you would do this:
<?php echo anchor(’blog/comments’, ’Click Here’);?>
Where “Click Here” is the name of the link, and “blog/comments” is the URI to the controller/method you wish to
link to.
“Extending” Helpers
To “extend” Helpers, create a file in your application/helpers/ folder with an identical name to the existing Helper,
but prefixed with MY_ (this item is configurable. See below.).
If all you need to do is add some functionality to an existing helper - perhaps add a function or two, or change how
a particular helper function operates - then it’s overkill to replace the entire helper with your version. In this case it’s
better to simply “extend” the Helper.
: The term “extend” is used loosely since Helper functions are procedural and discrete and cannot be extended in the
traditional programmatic sense. Under the hood, this gives you the ability to add to or or to replace the functions a
Helper provides.
For example,
to extend the native Array Helper you’ll
tion/helpers/MY_array_helper.php, and add or override functions:
create
a
file
named
applica-
// any_in_array() is not in the Array Helper, so it defines a new function
function any_in_array($needle, $haystack)
{
$needle = is_array($needle) ? $needle : array($needle);
386
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
foreach ($needle as $item)
{
if (in_array($item, $haystack))
{
return TRUE;
}
}
return FALSE;
}
// random_element() is included in Array Helper, so it overrides the native function
function random_element($array)
{
shuffle($array);
return array_pop($array);
}
Setting Your Own Prefix
The filename prefix for “extending” Helpers is the same used to extend libraries and core classes. To set your own
prefix, open your application/config/config.php file and look for this item:
$config[’subclass_prefix’] = ’MY_’;
Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.
Now What?
In the Table of Contents you’ll find a list of all the available Helper Files. Browse each one to see what they do.
10.12.7 Using CodeIgniter Libraries
All of the available libraries are located in your system/libraries/ directory. In most cases, to use one of these classes
involves initializing it within a controller using the following initialization method:
$this->load->library(’class_name’);
Where ‘class_name’ is the name of the class you want to invoke. For example, to load the Form Validation Library
you would do this:
$this->load->library(’form_validation’);
Once initialized you can use it as indicated in the user guide page corresponding to that class.
Additionally, multiple libraries can be loaded at the same time by passing an array of libraries to the load method.
Example:
$this->load->library(array(’email’, ’table’));
Creating Your Own Libraries
Please read the section of the user guide that discusses how to create your own libraries.
10.12. General Topics
387
CodeIgniter Documentation, 3.0-dev
10.12.8 Creating Libraries
When we use the term “Libraries” we are normally referring to the classes that are located in the libraries directory
and described in the Class Reference of this user guide. In this case, however, we will instead describe how you can
create your own libraries within your application/libraries directory in order to maintain separation between your local
resources and the global framework resources.
As an added bonus, CodeIgniter permits your libraries to extend native classes if you simply need to add some functionality to an existing library. Or you can even replace native libraries just by placing identically named versions in
your application/libraries directory.
In summary:
• You can create entirely new libraries.
• You can extend native libraries.
• You can replace native libraries.
The page below explains these three concepts in detail.
: The Database classes can not be extended or replaced with your own classes. All other classes are able to be
replaced/extended.
Storage
Your library classes should be placed within your application/libraries directory, as this is where CodeIgniter will look
for them when they are initialized.
Naming Conventions
• File names must be capitalized. For example: Myclass.php
• Class declarations must be capitalized. For example: class Myclass
• Class names and file names must match.
The Class File
Classes should have this basic prototype:
<?php if ( ! defined(’BASEPATH’)) exit(’No direct script access allowed’);
class Someclass {
public function some_method()
{
}
}
/* End of file Someclass.php */
: We are using the name Someclass purely as an example.
388
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Using Your Class
From within any of your Controller methods you can initialize your class using the standard:
$this->load->library(’someclass’);
Where someclass is the file name, without the ”.php” file extension. You can submit the file name capitalized or lower
case. CodeIgniter doesn’t care.
Once loaded you can access your class using the lower case version:
$this->someclass->some_method();
// Object instances will always be lower case
Passing Parameters When Initializing Your Class
In the library loading method you can dynamically pass data as an array via the second parameter and it will be passed
to your class constructor:
$params = array(’type’ => ’large’, ’color’ => ’red’);
$this->load->library(’someclass’, $params);
If you use this feature you must set up your class constructor to expect data:
<?php defined(’BASEPATH’) OR exit(’No direct script access allowed’);
class Someclass {
public function __construct($params)
{
// Do something with $params
}
}
You can also pass parameters stored in a config file. Simply create a config file named identically to the class file name
and store it in your application/config/ directory. Note that if you dynamically pass parameters as described above,
the config file option will not be available.
Utilizing CodeIgniter Resources within Your Library
To access CodeIgniter’s native resources within your library use the get_instance() method. This method returns
the CodeIgniter super object.
Normally from within your controller methods you will call any of the available CodeIgniter methods using the $this
construct:
$this->load->helper(’url’);
$this->load->library(’session’);
$this->config->item(’base_url’);
// etc.
$this, however, only works directly within your controllers, your models, or your views. If you would like to use
CodeIgniter’s classes from within your own custom classes you can do so as follows:
First, assign the CodeIgniter object to a variable:
$CI =& get_instance();
10.12. General Topics
389
CodeIgniter Documentation, 3.0-dev
Once you’ve assigned the object to a variable, you’ll use that variable instead of $this:
$CI =& get_instance();
$CI->load->helper(’url’);
$CI->load->library(’session’);
$CI->config->item(’base_url’);
// etc.
: You’ll notice that the above get_instance() function is being passed by reference:
$CI =& get_instance();
This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a
copy of it.
However, since a library is a class, it would be better if you take full advantage of the OOP principles. So, in order
to be able to use the CodeIgniter super-object in all of the class methods, you’re encouraged to assign it to a property
instead:
class Example_library {
protected $CI;
// We’ll use a constructor, as you can’t directly call a function
// from a property definition.
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
}
public function foo()
{
$this->CI->load->helper(’url’);
redirect();
}
public function bar()
{
echo $this->CI->config_item(’base_url’);
}
}
Replacing Native Libraries with Your Versions
Simply by naming your class files identically to a native library will cause CodeIgniter to use it instead of the native
one. To use this feature you must name the file and the class declaration exactly the same as the native library. For
example, to replace the native Email library you’ll create a file named application/libraries/Email.php, and declare
your class with:
class CI_Email {
}
Note that most native classes are prefixed with CI_.
390
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
To load your library you’ll see the standard loading method:
$this->load->library(’email’);
: At this time the Database classes can not be replaced with your own versions.
Extending Native Libraries
If all you need to do is add some functionality to an existing library - perhaps add a method or two - then it’s overkill
to replace the entire library with your version. In this case it’s better to simply extend the class. Extending a class is
nearly identical to replacing a class with a couple exceptions:
• The class declaration must extend the parent class.
• Your new class name and filename must be prefixed with MY_ (this item is configurable. See below.).
For example, to extend the native Email class you’ll create a file named application/libraries/MY_Email.php, and
declare your class with:
class MY_Email extends CI_Email {
}
If you need to use a constructor in your class make sure you extend the parent constructor:
class MY_Email extends CI_Email {
public function __construct($config = array())
{
parent::__construct($config);
}
}
: Not all of the libraries have the same (or any) parameters in their constructor. Take a look at the library that you’re
extending first to see how it should be implemented.
Loading Your Sub-class
To load your sub-class you’ll use the standard syntax normally used. DO NOT include your prefix. For example, to
load the example above, which extends the Email class, you will use:
$this->load->library(’email’);
Once loaded you will use the class variable as you normally would for the class you are extending. In the case of the
email class all calls will use:
$this->email->some_method();
Setting Your Own Prefix
To set your own sub-class prefix, open your application/config/config.php file and look for this item:
10.12. General Topics
391
CodeIgniter Documentation, 3.0-dev
$config[’subclass_prefix’] = ’MY_’;
Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.
10.12.9 Using CodeIgniter Drivers
Drivers are a special type of Library that has a parent class and any number of potential child classes. Child classes
have access to the parent class, but not their siblings. Drivers provide an elegant syntax in your controllers for libraries
that benefit from or require being broken down into discrete classes.
Drivers are found in the system/libraries/ directory, in their own sub-directory which is identically named to the parent
library class. Also inside that directory is a subdirectory named drivers, which contains all of the possible child class
files.
To use a driver you will initialize it within a controller using the following initialization method:
$this->load->driver(’class_name’);
Where class name is the name of the driver class you want to invoke. For example, to load a driver named
“Some_parent” you would do this:
$this->load->driver(’some_parent’);
Methods of that class can then be invoked with:
$this->some_parent->some_method();
The child classes, the drivers themselves, can then be called directly through the parent class, without initializing them:
$this->some_parent->child_one->some_method();
$this->some_parent->child_two->another_method();
Creating Your Own Drivers
Please read the section of the user guide that discusses how to create your own drivers.
10.12.10 Creating Drivers
Driver Directory and File Structure
Sample driver directory and file structure layout:
• /application/libraries/Driver_name
– Driver_name.php
– drivers
* Driver_name_subclass_1.php
* Driver_name_subclass_2.php
* Driver_name_subclass_3.php
: In order to maintain compatibility on case-sensitive file systems, the Driver_name directory must be named in the
format returned by ucfirst().
392
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
10.12.11 Creating Core System Classes
Every time CodeIgniter runs there are several base classes that are initialized automatically as part of the core framework. It is possible, however, to swap any of the core system classes with your own versions or even extend the core
versions.
Most users will never have any need to do this, but the option to replace or extend them does exist for those who
would like to significantly alter the CodeIgniter core.
: Messing with a core system class has a lot of implications, so make sure you know what you are doing before
attempting it.
System Class List
The following is a list of the core system files that are invoked every time CodeIgniter runs:
• Benchmark
• Config
• Controller
• Exceptions
• Hooks
• Input
• Language
• Loader
• Log
• Output
• Router
• Security
• URI
• Utf8
Replacing Core Classes
To use one of your own system classes instead of a default one simply place your version inside your local application/core/ directory:
application/core/some_class.php
If this directory does not exist you can create it.
Any file named identically to one from the list above will be used instead of the one normally used.
Please note that your class must use CI as a prefix. For example, if your file is named Input.php the class will be
named:
class CI_Input {
}
10.12. General Topics
393
CodeIgniter Documentation, 3.0-dev
Extending Core Class
If all you need to do is add some functionality to an existing library - perhaps add a method or two - then it’s overkill
to replace the entire library with your version. In this case it’s better to simply extend the class. Extending a class is
nearly identical to replacing a class with a couple exceptions:
• The class declaration must extend the parent class.
• Your new class name and filename must be prefixed with MY_ (this item is configurable. See below.).
For example, to extend the native Input class you’ll create a file named application/core/MY_Input.php, and declare
your class with:
class MY_Input extends CI_Input {
}
: If you need to use a constructor in your class make sure you extend the parent constructor:
class MY_Input extends CI_Input {
public function __construct()
{
parent::__construct();
}
}
Tip: Any functions in your class that are named identically to the methods in the parent class will be used instead of
the native ones (this is known as “method overriding”). This allows you to substantially alter the CodeIgniter core.
If you are extending the Controller core class, then be sure to extend your new class in your application controller’s
constructors.
class Welcome extends MY_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view(’welcome_message’);
}
}
Setting Your Own Prefix
To set your own sub-class prefix, open your application/config/config.php file and look for this item:
$config[’subclass_prefix’] = ’MY_’;
Please note that all native CodeIgniter libraries are prefixed with CI_ so DO NOT use that as your prefix.
394
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
10.12.12 Creating Ancillary Classes
In some cases you may want to develop classes that exist apart from your controllers but have the ability to utilize all
of CodeIgniter’s resources. This is easily possible as you’ll see.
get_instance()
get_instance()
object of class CI_Controller
Any class that you instantiate within your controller methods can access CodeIgniter’s native resources simply
by using the get_instance() function. This function returns the main CodeIgniter object.
Normally, to call any of the available CodeIgniter methods requires you to use the $this construct:
$this->load->helper(’url’);
$this->load->library(’session’);
$this->config->item(’base_url’);
// etc.
$this, however, only works within your controllers, your models, or your views. If you would like to use
CodeIgniter’s classes from within your own custom classes you can do so as follows:
First, assign the CodeIgniter object to a variable:
$CI =& get_instance();
Once you’ve assigned the object to a variable, you’ll use that variable instead of $this:
$CI =& get_instance();
$CI->load->helper(’url’);
$CI->load->library(’session’);
$CI->config->item(’base_url’);
// etc.
: You’ll notice that the above get_instance() function is being passed by reference:
$CI =& get_instance();
This is very important. Assigning by reference allows you to use the original CodeIgniter object rather than creating a
copy of it.
Furthermore, if you’ll be using get_intance() inside anoter class, then it would be better if you assign it to a
property. This way, you won’t need to call get_instance() in every single method.
Example:
class Example {
protected $CI;
// We’ll use a constructor, as you can’t directly call a function
// from a property definition.
public function __construct()
{
// Assign the CodeIgniter super-object
$this->CI =& get_instance();
10.12. General Topics
395
CodeIgniter Documentation, 3.0-dev
}
public function foo()
{
$this->CI->load->helper(’url’);
redirect();
}
public function bar()
{
$this->CI->config_item(’base_url’);
}
}
In the above example, both methods foo() and bar() will work after you instantiate the Example class, without
the need to call get_instance() in each of them.
10.12.13 Hooks - Extending the Framework Core
CodeIgniter’s Hooks feature provides a means to tap into and modify the inner workings of the framework without
hacking the core files. When CodeIgniter runs it follows a specific execution process, diagramed in the Application
Flow page. There may be instances, however, where you’d like to cause some action to take place at a particular stage
in the execution process. For example, you might want to run a script right before your controllers get loaded, or right
after, or you might want to trigger one of your own scripts in some other location.
Enabling Hooks
The hooks feature can be globally enabled/disabled by setting the following item in the application/config/config.php
file:
$config[’enable_hooks’] = TRUE;
Defining a Hook
Hooks are defined in application/config/hooks.php file. Each hook is specified as an array with this prototype:
$hook[’pre_controller’] = array(
’class’
=> ’MyClass’,
’function’ => ’Myfunction’,
’filename’ => ’Myclass.php’,
’filepath’ => ’hooks’,
’params’
=> array(’beer’, ’wine’, ’snacks’)
);
Notes:
The array index correlates to the name of the particular hook point you want to use. In the above example the hook
point is pre_controller. A list of hook points is found below. The following items should be defined in your associative
hook array:
• class The name of the class you wish to invoke. If you prefer to use a procedural function instead of a class,
leave this item blank.
• function The function (or method) name you wish to call.
396
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• filename The file name containing your class/function.
• filepath The name of the directory containing your script. Note: Your script must be located in a directory
INSIDE your application/ directory, so the file path is relative to that directory. For example, if your script is
located in application/hooks/, you will simply use ‘hooks’ as your filepath. If your script is located in application/hooks/utilities/ you will use ‘hooks/utilities’ as your filepath. No trailing slash.
• params Any parameters you wish to pass to your script. This item is optional.
Multiple Calls to the Same Hook
If want to use the same hook point with more then one script, simply make your array declaration multi-dimensional,
like this:
$hook[’pre_controller’][] = array(
’class’
=> ’MyClass’,
’function’ => ’MyMethod’,
’filename’ => ’Myclass.php’,
’filepath’ => ’hooks’,
’params’
=> array(’beer’, ’wine’, ’snacks’)
);
$hook[’pre_controller’][] = array(
’class’
=> ’MyOtherClass’,
’function’ => ’MyOtherMethod’,
’filename’ => ’Myotherclass.php’,
’filepath’ => ’hooks’,
’params’
=> array(’red’, ’yellow’, ’blue’)
);
Notice the brackets after each array index:
$hook[’pre_controller’][]
This permits you to have the same hook point with multiple scripts. The order you define your array will be the
execution order.
Hook Points
The following is a list of available hook points.
• pre_system Called very early during system execution. Only the benchmark and hooks class have been loaded
at this point. No routing or other processes have happened.
• pre_controller Called immediately prior to any of your controllers being called. All base classes, routing, and
security checks have been done.
• post_controller_constructor Called immediately after your controller is instantiated, but prior to any method
calls happening.
• post_controller Called immediately after your controller is fully executed.
• display_override Overrides the _display() method, used to send the finalized page to the web browser at
the end of system execution. This permits you to use your own display methodology. Note that you will need
to reference the CI superobject with $this->CI =& get_instance() and then the finalized data will be
available by calling $this->CI->output->get_output().
• cache_override Enables you to call your own method instead of the _display_cache() method in the
Output Library. This permits you to use your own cache display mechanism.
10.12. General Topics
397
CodeIgniter Documentation, 3.0-dev
• post_system Called after the final rendered page is sent to the browser, at the end of system execution after the
finalized data is sent to the browser.
10.12.14 Auto-loading Resources
CodeIgniter comes with an “Auto-load” feature that permits libraries, helpers, and models to be initialized automatically every time the system runs. If you need certain resources globally throughout your application you should
consider auto-loading them for convenience.
The following items can be loaded automatically:
• Classes found in the libraries/ directory
• Helper files found in the helpers/ directory
• Custom config files found in the config/ directory
• Language files found in the system/language/ directory
• Models found in the models/ folder
To autoload resources, open the application/config/autoload.php file and add the item you want loaded to the autoload
array. You’ll find instructions in that file corresponding to each type of item.
: Do not include the file extension (.php) when adding items to the autoload array.
10.12.15 Common Functions
CodeIgniter uses a few functions for its operation that are globally defined, and are available to you at any point. These
do not require loading any libraries or helpers.
is_php()
is_php($version = ‘5.3.0’)
• $version (string) – Version number
bool
Determines of the PHP version being used is greater than the supplied version number.
Example:
if (is_php(’5.3’))
{
$str = quoted_printable_encode($str);
}
Returns boolean TRUE if the installed version of PHP is equal to or greater than the supplied version number. Returns
FALSE if the installed version of PHP is lower than the supplied version number.
is_really_writable()
is_really_writable($file)
398
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• $file (string) – File path
bool
is_writable() returns TRUE on Windows servers when you really can’t write to the file as the OS reports to PHP
as FALSE only if the read-only attribute is marked.
This function determines if a file is actually writable by attempting to write to it first. Generally only recommended
on platforms where this information may be unreliable.
Example:
if (is_really_writable(’file.txt’))
{
echo "I could write to this if I wanted to";
}
else
{
echo "File is not writable";
}
config_item()
config_item($key)
• $key (string) – Config item key
mixed
The Config Library is the preferred way of accessing configuration information, however config_item() can be
used to retrieve single keys. See Config Library documentation for more information.
show_error()
show_error($message, $status_code, $heading = ‘An Error Was Encountered’)
• $message (mixed) – Error message
• $status_code (int) – HTTP Response status code
• $heading (string) – Error page heading
void
This function calls CI_Exception::show_error(). For more info, please see the Error Handling documentation.
show_404()
show_404($page = ‘’, $log_error = TRUE)
• $page (string) – URI string
• $log_error (bool) – Whether to log the error
void
10.12. General Topics
399
CodeIgniter Documentation, 3.0-dev
This function calls CI_Exception::show_404(). For more info, please see the Error Handling documentation.
log_message()
log_message($level, $message)
• $level (string) – Log level: ‘error’, ‘debug’ or ‘info’
• $message (string) – Message to log
void
This function is an alias for CI_Log::write_log(). For more info, please see the Error Handling documentation.
set_status_header()
set_status_header($code, $text = ‘’)
• $code (int) – HTTP Reponse status code
• $text (string) – A custom message to set with the status code
void
Permits you to manually set a server status header. Example:
set_status_header(401);
// Sets the header as: Unauthorized
See here for a full list of headers.
remove_invisible_characters()
remove_invisible_characters($str, $url_encoded = TRUE)
• $str (string) – Input string
• $url_encoded (bool) – Whether to remove URL-encoded characters as well
string
This function prevents inserting NULL characters between ASCII characters, like Java\0script.
Example:
remove_invisible_characters(’Java\\0script’);
// Returns: ’Javascript’
html_escape()
html_escape($var)
• $var (mixed) – Variable to escape (string or array)
400
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
mixed
This function acts as an alias for PHP’s native htmlspecialchars() function, with the advantage of being able
to accept an array of strings.
It is useful in preventing Cross Site Scripting (XSS).
get_mimes()
get_mimes()
array
This function returns a reference to the MIMEs array from application/config/mimes.php.
is_https()
is_https()
bool
Returns TRUE if a secure (HTTPS) connection is used and FALSE in any other case (including non-HTTP requests).
is_cli()
is_cli()
bool
Returns TRUE if the application is run through the command line and FALSE if not.
: This function checks both if the PHP_SAPI value is ‘cli’ or if the STDIN constant is defined.
function_usable()
function_usable($function_name)
• $function_name (string) – Function name
bool
Returns TRUE if a function exists and is usable, FALSE otherwise.
This function runs a function_exists() check and if the Suhosin extension <http://www.hardenedphp.net/suhosin/> is loaded, checks if it doesn’t disable the function being checked.
It is useful if you want to check for the availability of functions such as eval() and exec(), which are dangerous
and might be disabled on servers with highly restrictive security policies.
10.12.16 URI Routing
Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. The
segments in a URI normally follow this pattern:
10.12. General Topics
401
CodeIgniter Documentation, 3.0-dev
example.com/class/function/id/
In some instances, however, you may want to remap this relationship so that a different class/method can be called
instead of the one corresponding to the URL.
For example, let’s say you want your URLs to have this prototype:
example.com/product/1/
example.com/product/2/
example.com/product/3/
example.com/product/4/
Normally the second segment of the URL is reserved for the method name, but in the example above it instead has a
product ID. To overcome this, CodeIgniter allows you to remap the URI handler.
Setting your own routing rules
Routing rules are defined in your application/config/routes.php file. In it you’ll see an array called $route that permits you to specify your own routing criteria. Routes can either be specified using wildcards or Regular Expressions.
Wildcards
A typical wildcard route might look something like this:
$route[’product/:num’] = ’catalog/product_lookup’;
In a route, the array key contains the URI to be matched, while the array value contains the destination it should be
re-routed to. In the above example, if the literal word “product” is found in the first segment of the URL, and a number
is found in the second segment, the “catalog” class and the “product_lookup” method are instead used.
You can match literal values or you can use two wildcard types:
(:num) will match a segment containing only numbers. (:any) will match a segment containing any character (except
for ‘/’, which is the segment delimiter).
: Wildcards are actually aliases for regular expressions, with :any being translated to [^/]+ and :num to [0-9]+,
respectively.
: Routes will run in the order they are defined. Higher routes will always take precedence over lower ones.
: Route rules are not filters! Setting a rule of e.g. ‘foo/bar/(:num)’ will not prevent controller Foo and method bar to
be called with a non-numeric value if that is a valid route.
Examples
Here are a few routing examples:
$route[’journals’] = ’blogs’;
A URL containing the word “journals” in the first segment will be remapped to the “blogs” class.
$route[’blog/joe’] = ’blogs/users/34’;
402
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
A URL containing the segments blog/joe will be remapped to the “blogs” class and the “users” method. The ID will
be set to “34”.
$route[’product/(:any)’] = ’catalog/product_lookup’;
A URL with “product” as the first segment, and anything in the second will be remapped to the “catalog” class and the
“product_lookup” method.
$route[’product/(:num)’] = ’catalog/product_lookup_by_id/$1’;
A URL with “product” as the first segment, and a number in the second will be remapped to the “catalog” class and
the “product_lookup_by_id” method passing in the match as a variable to the method.
: Do not use leading/trailing slashes.
Regular Expressions
If you prefer you can use regular expressions to define your routing rules. Any valid regular expression is allowed, as
are back-references.
: If you use back-references you must use the dollar syntax rather than the double backslash syntax.
A typical RegEx route might look something like this:
$route[’products/([a-z]+)/(\d+)’] = ’$1/id_$2’;
In the above example, a URI similar to products/shirts/123 would instead call the “shirts” controller class and the
“id_123” method.
With regular expressions, you can also catch a segment containing a forward slash (‘/’), which would usually represent
the delimiter between multiple segments. For example, if a user accesses a password protected area of your web
application and you wish to be able to redirect them back to the same page after they log in, you may find this example
useful:
$route[’login/(.+)’] = ’auth/login/$1’;
That will call the “auth” controller class and its login() method, passing everything contained in the URI after
login/ as a parameter.
For those of you who don’t know regular expressions and want to learn more about them, regular-expressions.info
<http://www.regular-expressions.info/> might be a good starting point.
: You can also mix and match wildcards with regular expressions.
Callbacks
If you are using PHP >= 5.3 you can use callbacks in place of the normal routing rules to process the back-references.
Example:
$route[’products/([a-zA-Z]+)/edit/(\d+)’] = function ($product_type, $id)
{
return ’catalog/product_edit/’ . strtolower($product_type) . ’/’ . $id;
};
10.12. General Topics
403
CodeIgniter Documentation, 3.0-dev
Using HTTP verbs in routes
It is possible to use HTTP verbs (request method) to define your routing rules. This is particularly useful when building
RESTful applications. You can use standard HTTP verbs (GET, PUT, POST, DELETE, PATCH) or a custom one such
(e.g. PURGE). HTTP verb rules are case-insensitive. All you need to do is to add the verb as an array key to your
route. Example:
$route[’products’][’put’] = ’product/insert’;
In the above example, a PUT request to URI “products” would call the Product::insert() controller method.
$route[’products/(:num)’][’DELETE’] = ’product/delete/$1’;
A DELETE request to URL with “products” as first the segment and a number in the second will be mapped to the
Product::delete() method, passing the numeric value as the first parameter.
Using HTTP verbs is of course, optional.
Reserved Routes
There are three reserved routes:
$route[’default_controller’] = ’welcome’;
This route indicates which controller class should be loaded if the URI contains no data, which will be the case when
people load your root URL. In the above example, the “welcome” class would be loaded. You are encouraged to
always have a default route otherwise a 404 page will appear by default.
$route[’404_override’] = ’’;
This route indicates which controller class should be loaded if the requested controller is not found. It will override
the default 404 error page. It won’t affect to the show_404() function, which will continue loading the default
error_404.php file at application/views/errors/error_404.php.
$route[’translate_uri_dashes’] = FALSE;
As evident by the boolean value, this is not exactly a route. This option enables you to automatically replace dashes
(‘-‘) with underscores in the controller and method URI segments, thus saving you additional route entries if you need
to do that. This is required, because the dash isn’t a valid class or method name character and would cause a fatal error
if you try to use it.
: The reserved routes must come before any wildcard or regular expression routes.
10.12.17 Error Handling
CodeIgniter lets you build error reporting into your applications using the functions described below. In addition, it
has an error logging class that permits error and debugging messages to be saved as text files.
: By default, CodeIgniter displays all PHP errors. You might wish to change this behavior once your development
is complete. You’ll find the error_reporting() function located at the top of your main index.php file. Disabling error
reporting will NOT prevent log files from being written if there are errors.
Unlike most systems in CodeIgniter, the error functions are simple procedural interfaces that are available globally
throughout the application. This approach permits error messages to get triggered without having to worry about
class/function scoping.
404
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
CodeIgniter also returns a status code whenever a portion of the core calls exit(). This exit status code is separate
from the HTTP status code, and serves as a notice to other processes that may be watching of whether the script
completed successfully, or if not, what kind of problem it encountered that caused it to abort. These values are defined
in application/config/constants.php. While exit status codes are most useful in CLI settings, returning the proper code
helps server software keep track of your scripts and the health of your application.
The following functions let you generate errors:
show_error()
show_error($message, $status_code, $heading = ‘An Error Was Encountered’)
• $message (mixed) – Error message
• $status_code (int) – HTTP Response status code
• $heading (string) – Error page heading
void
This function will display the error message supplied to it using the following error template:
application/views/errors/error_general.php
The optional parameter $status_code determines what HTTP status code should be sent with the error. If
$status_code is less than 100, the HTTP status code will be set to 500, and the exit status code will be set to
$status_code + EXIT__AUTO_MIN. If that value is larger than EXIT__AUTO_MAX, or if $status_code
is 100 or higher, the exit status code will be set to EXIT_ERROR. You can check in application/config/constants.php
for more detail.
show_404()
show_404($page = ‘’, $log_error = TRUE)
• $page (string) – URI string
• $log_error (bool) – Whether to log the error
void
This function will display the 404 error message supplied to it using the following error template:
application/views/errors/error_404.php
The function expects the string passed to it to be the file path to the page that isn’t found. The exit status code will be
set to EXIT_UNKNOWN_FILE. Note that CodeIgniter automatically shows 404 messages if controllers are not found.
CodeIgniter automatically logs any show_404() calls. Setting the optional second parameter to FALSE will skip
logging.
log_message()
log_message($level, $message, $php_error = FALSE)
• $level (string) – Log level: ‘error’, ‘debug’ or ‘info’
10.12. General Topics
405
CodeIgniter Documentation, 3.0-dev
• $message (string) – Message to log
• $php_error (bool) – Whether we’re logging a native PHP error message
void
This function lets you write messages to your log files. You must supply one of three “levels” in the first parameter,
indicating what type of message it is (debug, error, info), with the message itself in the second parameter.
Example:
if ($some_var == ’’)
{
log_message(’error’, ’Some variable did not contain a value.’);
}
else
{
log_message(’debug’, ’Some variable was correctly set’);
}
log_message(’info’, ’The purpose of some variable is to provide some value.’);
There are three message types:
1. Error Messages. These are actual errors, such as PHP errors or user errors.
2. Debug Messages. These are messages that assist in debugging. For example, if a class has been initialized, you
could log this as debugging info.
3. Informational Messages. These are the lowest priority messages, simply giving information regarding some
process. CodeIgniter doesn’t natively generate any info messages but you may want to in your application.
: In order for the log file to actually be written, the logs directory must be writable. In addition, you must set the
“threshold” for logging in application/config/config.php. You might, for example, only want error messages to be
logged, and not the other two types. If you set it to zero logging will be disabled.
10.12.18 Web Page Caching
CodeIgniter lets you cache your pages in order to achieve maximum performance.
Although CodeIgniter is quite fast, the amount of dynamic information you display in your pages will correlate directly
to the server resources, memory, and processing cycles utilized, which affect your page load speeds. By caching your
pages, since they are saved in their fully rendered state, you can achieve performance that nears that of static web
pages.
How Does Caching Work?
Caching can be enabled on a per-page basis, and you can set the length of time that a page should remain cached
before being refreshed. When a page is loaded for the first time, the cache file will be written to your application/cache
folder. On subsequent page loads the cache file will be retrieved and sent to the requesting user’s browser. If it has
expired, it will be deleted and refreshed before being sent to the browser.
Enabling Caching
To enable caching, put the following tag in any of your controller methods:
406
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$this->output->cache($n);
Where $n is the number of minutes you wish the page to remain cached between refreshes.
The above tag can go anywhere within a method. It is not affected by the order that it appears, so place it wherever it
seems most logical to you. Once the tag is in place, your pages will begin being cached.
: Because of the way CodeIgniter stores content for output, caching will only work if you are generating display for
your controller with a view.
: Before the cache files can be written you must set the file permissions on your application/cache/ directory such
that it is writable.
Deleting Caches
If you no longer wish to cache a file you can remove the caching tag and it will no longer be refreshed when it expires.
: Removing the tag will not delete the cache immediately. It will have to expire normally.
If you need to manually delete the cache, you can use the delete_cache() method:
// Deletes cache for the currently requested URI
$this->output->delete_cache();
// Deletes cache for /foo/bar
$this->output->delete_cache(’/foo/bar’);
10.12.19 Profiling Your Application
The Profiler Class will display benchmark results, queries you have run, and $_POST data at the bottom of your pages.
This information can be useful during development in order to help with debugging and optimization.
Initializing the Class
: This class does NOT need to be initialized. It is loaded automatically by the Output Library if profiling is enabled
as shown below.
Enabling the Profiler
To enable the profiler place the following line anywhere within your Controller methods:
$this->output->enable_profiler(TRUE);
When enabled a report will be generated and inserted at the bottom of your pages.
To disable the profiler you will use:
$this->output->enable_profiler(FALSE);
10.12. General Topics
407
CodeIgniter Documentation, 3.0-dev
Setting Benchmark Points
In order for the Profiler to compile and display your benchmark data you must name your mark points using specific
syntax.
Please read the information on setting Benchmark points in the Benchmark Library page.
Enabling and Disabling Profiler Sections
Each section of Profiler data can be enabled or disabled by setting a corresponding config variable to TRUE or FALSE.
This can be done one of two ways. First, you can set application wide defaults with the application/config/profiler.php
config file.
Example:
$config[’config’]
$config[’queries’]
= FALSE;
= FALSE;
In your controllers, you can override the defaults
set_profiler_sections() method of the Output Library:
and
config
file
values
by
calling
the
$sections = array(
’config’ => TRUE,
’queries’ => TRUE
);
$this->output->set_profiler_sections($sections);
Available sections and the array key used to access them are described in the table below.
Key
benchmarks
config
controller_info
get
http_headers
memory_usage
post
queries
uri_string
session_data
query_toggle_count
Description
Elapsed time of Benchmark points and total execution time
CodeIgniter Config variables
The Controller class and method requested
Any GET data passed in the request
The HTTP headers for the current request
Amount of memory consumed by the current request, in bytes
Any POST data passed in the request
Listing of all database queries executed, including execution time
The URI of the current request
Data stored in the current session
The number of queries after which the query block will default to hidden.
Default
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
25
10.12.20 Running via the CLI
As well as calling an applications Controllers via the URL in a browser they can also be loaded via the command-line
interface (CLI).
Page Contents
• Running via the CLI
– What is the CLI?
– Why run via the command-line?
– Let’s try it: Hello World!
– That’s it!
408
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
What is the CLI?
The command-line interface is a text-based method of interacting with computers. For more information, check the
Wikipedia article.
Why run via the command-line?
There are many reasons for running CodeIgniter from the command-line, but they are not always obvious.
• Run your cron-jobs without needing to use wget or curl
• Make your cron-jobs inaccessible from being loaded in the URL by checking the return value of is_cli().
• Make interactive “tasks” that can do things like set permissions, prune cache folders, run backups, etc.
• Integrate with other applications in other languages. For example, a random C++ script could call one command
and run code in your models!
Let’s try it: Hello World!
Let’s create a simple controller so you can see it in action. Using your text editor, create a file called Tools.php, and
put the following code in it:
<?php
class Tools extends CI_Controller {
public function message($to = ’World’)
{
echo "Hello {$to}!".PHP_EOL;
}
}
Then save the file to your application/controllers/ folder.
Now normally you would visit the your site using a URL similar to this:
example.com/index.php/tools/message/to
Instead, we are going to open Terminal in Mac/Linux or go to Run > “cmd” in Windows and navigate to our
CodeIgniter project.
$ cd /path/to/project;
$ php index.php tools message
If you did it right, you should see Hello World! printed.
$ php index.php tools message "John Smith"
Here we are passing it a argument in the same way that URL parameters work. “John Smith” is passed as a argument
and output is:
Hello John Smith!
That’s it!
That, in a nutshell, is all there is to know about controllers on the command line. Remember that this is just a normal
controller, so routing and _remap() works fine.
10.12. General Topics
409
CodeIgniter Documentation, 3.0-dev
10.12.21 Managing your Applications
By default it is assumed that you only intend to use CodeIgniter to manage one application, which you will build in
your application/ directory. It is possible, however, to have multiple sets of applications that share a single CodeIgniter
installation, or even to rename or relocate your application directory.
Renaming the Application Directory
If you would like to rename your application directory you may do so as long as you open your main index.php file
and set its name using the $application_folder variable:
$application_folder = ’application’;
Relocating your Application Directory
It is possible to move your application directory to a different location on your server than your web root. To do so
open your main index.php and set a full server path in the $application_folder variable:
$application_folder = ’/path/to/your/application’;
Running Multiple Applications with one CodeIgniter Installation
If you would like to share a common CodeIgniter installation to manage several different applications simply put all
of the directories located inside your application directory into their own sub-directory.
For example, let’s say you want to create two applications, named “foo” and “bar”. You could structure your application directories like this:
applications/foo/
applications/foo/config/
applications/foo/controllers/
applications/foo/errors/
applications/foo/libraries/
applications/foo/models/
applications/foo/views/
applications/bar/
applications/bar/config/
applications/bar/controllers/
applications/bar/errors/
applications/bar/libraries/
applications/bar/models/
applications/bar/views/
To select a particular application for use requires that you open your main index.php file and set the
$application_folder variable. For example, to select the “foo” application for use you would do this:
$application_folder = ’applications/foo’;
: Each of your applications will need its own index.php file which calls the desired application. The index.php file
can be named anything you want.
410
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
10.12.22 Handling Multiple Environments
Developers often desire different system behavior depending on whether an application is running in a development
or production environment. For example, verbose error output is something that would be useful while developing an
application, but it may also pose a security issue when “live”.
The ENVIRONMENT Constant
By default, CodeIgniter comes with the environment constant set to use the value provided in
$_SERVER[’CI_ENV’], otherwise defaults to ‘development’. At the top of index.php, you will see:
define(’ENVIRONMENT’, isset($_SERVER[’CI_ENV’]) ? $_SERVER[’CI_ENV’] : ’development’);
This server variable can be set in your .htaccess file, or Apache config using SetEnv. Alternative methods are available
for nginx and other servers, or you can remove this logic entirely and set the constant based on the HTTP_HOST or
IP.
In addition to affecting some basic framework behavior (see the next section), you may use this constant in your own
development to differentiate between which environment you are running in.
Effects On Default Framework Behavior
There are some places in the CodeIgniter system where the ENVIRONMENT constant is used. This section describes
how default framework behavior is affected.
Error Reporting
Setting the ENVIRONMENT constant to a value of ‘development’ will cause all PHP errors to be rendered to the
browser when they occur. Conversely, setting the constant to ‘production’ will disable all error output. Disabling error
reporting in production is a good security practice.
Configuration Files
Optionally, you can have CodeIgniter load environment-specific configuration files. This may be useful for managing
things like differing API keys across multiple environments. This is described in more detail in the environment
section of the Config Class documentation.
10.12.23 Alternate PHP Syntax for View Files
If you do not utilize CodeIgniter’s template engine, you’ll be using pure PHP in your View files. To minimize the PHP
code in these files, and to make it easier to identify the code blocks it is recommended that you use PHPs alternative
syntax for control structures and short tag echo statements. If you are not familiar with this syntax, it allows you to
eliminate the braces from your code, and eliminate “echo” statements.
Automatic Short Tag Support
: If you find that the syntax described in this page does not work on your server it might be that “short tags” are
disabled in your PHP ini file. CodeIgniter will optionally rewrite short tags on-the-fly, allowing you to use that syntax
even if your server doesn’t support it. This feature can be enabled in your config/config.php file.
10.12. General Topics
411
CodeIgniter Documentation, 3.0-dev
Please note that if you do use this feature, if PHP errors are encountered in your view files, the error message and line
number will not be accurately shown. Instead, all errors will be shown as eval() errors.
Alternative Echos
Normally to echo, or print out a variable you would do this:
<?php echo $variable; ?>
With the alternative syntax you can instead do it this way:
<?=$variable?>
Alternative Control Structures
Controls structures, like if, for, foreach, and while can be written in a simplified format as well. Here is an example
using foreach:
<ul>
<?php foreach ($todo as $item): ?>
<li><?=$item?></li>
<?php endforeach; ?>
</ul>
Notice that there are no braces. Instead, the end brace is replaced with endforeach. Each of the control structures
listed above has a similar closing syntax: endif, endfor, endforeach, and endwhile
Also notice that instead of using a semicolon after each structure (except the last one), there is a colon. This is
important!
Here is another example, using if/elseif/else. Notice the colons:
<?php if ($username === ’sally’): ?>
<h3>Hi Sally</h3>
<?php elseif ($username === ’joe’): ?>
<h3>Hi Joe</h3>
<?php else: ?>
<h3>Hi unknown user</h3>
<?php endif; ?>
10.12.24 Security
This page describes some “best practices” regarding web security, and details CodeIgniter’s internal security features.
412
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
URI Security
CodeIgniter is fairly restrictive regarding which characters it allows in your URI strings in order to help minimize the
possibility that malicious data can be passed to your application. URIs may only contain the following:
• Alpha-numeric text (latin characters only)
• Tilde: ~
• Percent sign: %
• Period: .
• Colon: :
• Underscore: _
• Dash: • Space
Register_globals
During system initialization all global variables are unset, except those found in the $_GET, $_POST, and $_COOKIE
arrays. The unsetting routine is effectively the same as register_globals = off.
display_errors
In production environments, it is typically desirable to “disable” PHP’s error reporting by setting the internal display_errors flag to a value of 0. This disables native PHP errors from being rendered as output, which may potentially
contain sensitive information.
Setting CodeIgniter’s ENVIRONMENT constant in index.php to a value of ‘production’ will turn off these errors. In
development mode, it is recommended that a value of ‘development’ is used. More information about differentiating
between environments can be found on the Handling Environments page.
magic_quotes_runtime
The magic_quotes_runtime directive is turned off during system initialization so that you don’t have to remove slashes
when retrieving data from your database.
Best Practices
Before accepting any data into your application, whether it be POST data from a form submission, COOKIE data, URI
data, XML-RPC data, or even data from the SERVER array, you are encouraged to practice this three step approach:
1. Filter the data as if it were tainted.
2. Validate the data to ensure it conforms to the correct type, length, size, etc. (sometimes this step can replace
step one)
3. Escape the data before submitting it into your database.
CodeIgniter provides the following functions to assist in this process:
10.12. General Topics
413
CodeIgniter Documentation, 3.0-dev
XSS Filtering
CodeIgniter comes with a Cross Site Scripting filter. This filter looks for commonly used techniques to embed malicious JavaScript into your data, or other types of code that attempt to hijack cookies or do other malicious things. The
XSS Filter is described here.
Validate the data
CodeIgniter has a Form Validation Library that assists you in validating, filtering, and prepping your data.
Escape all data before database insertion
Never insert information into your database without escaping it. Please see the section that discusses database queries
for more information.
Hide your files
Another good security practice is to only leave your index.php and “assets” (e.g. .js, css and image files) under your
server’s webroot directory (most commonly named “htdocs/”). These are the only files that you would need to be
accessible from the web.
Allowing your visitors to see anything else would potentially allow them to access sensitive data, execute scripts, etc.
If you’re not allowed to do that, you can try using a .htaccess file to restrict access to those resources.
CodeIgniter will have an index.html file in all of its directories in an attempt to hide some of this data, but have it in
mind that this is not enough to prevent a serious attacker.
10.12.25 PHP Style Guide
The following page describes the coding styles adhered to when contributing to the development of CodeIgniter. There
is no requirement to use these styles in your own CodeIgniter application, though they are recommended.
414
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Table of Contents
• PHP Style Guide
– File Format
* TextMate
* BBEdit
– PHP Closing Tag
– File Naming
– Class and Method Naming
– Variable Names
– Commenting
– Constants
– TRUE, FALSE, and NULL
– Logical Operators
– Comparing Return Values and Typecasting
– Debugging Code
– Whitespace in Files
– Compatibility
– One File per Class
– Whitespace
– Line Breaks
– Code Indenting
– Bracket and Parenthetic Spacing
– Localized Text
– Private Methods and Variables
– PHP Errors
– Short Open Tags
– One Statement Per Line
– Strings
– SQL Queries
– Default Function Arguments
File Format
Files should be saved with Unicode (UTF-8) encoding. The BOM should not be used. Unlike UTF-16 and UTF-32,
there’s no byte order to indicate in a UTF-8 encoded file, and the BOM can have a negative side effect in PHP of
sending output, preventing the application from being able to set its own headers. Unix line endings should be used
(LF).
Here is how to apply these settings in some of the more common text editors. Instructions for your text editor may
vary; check your text editor’s documentation.
TextMate
1. Open the Application Preferences
2. Click Advanced, and then the “Saving” tab
3. In “File Encoding”, select “UTF-8 (recommended)”
4. In “Line Endings”, select “LF (recommended)”
5. Optional: Check “Use for existing files as well” if you wish to modify the line endings of files you open to your
new preference.
10.12. General Topics
415
CodeIgniter Documentation, 3.0-dev
BBEdit
1. Open the Application Preferences
2. Select “Text Encodings” on the left.
3. In “Default text encoding for new documents”, select “Unicode (UTF-8, no BOM)”
4. Optional: In “If file’s encoding can’t be guessed, use”, select “Unicode (UTF-8, no BOM)”
5. Select “Text Files” on the left.
6. In “Default line breaks”, select “Mac OS X and Unix (LF)”
PHP Closing Tag
The PHP closing tag on a PHP document ?> is optional to the PHP parser. However, if used, any whitespace following
the closing tag, whether introduced by the developer, user, or an FTP application, can cause unwanted output, PHP
errors, or if the latter are suppressed, blank pages. For this reason, all PHP files should OMIT the closing PHP tag,
and instead use a comment block to mark the end of file and its location relative to the application root. This allows
you to still identify a file as being complete and not truncated.
INCORRECT:
<?php
echo "Here’s my code!";
?>
CORRECT:
<?php
echo "Here’s my code!";
/* End of file Myfile.php */
/* Location: ./system/modules/mymodule/myfile.php */
: There should be no empty line or newline character(s) following the closing comments. If you happen to see one
when submitting a pull request, please check your IDE settings and fix it.
File Naming
Class files must be named in a Ucfirst-like manner, while any other file name (configurations, views, generic scripts,
etc.) should be in all lowercase.
INCORRECT:
somelibrary.php
someLibrary.php
SOMELIBRARY.php
Some_Library.php
Application_config.php
Application_Config.php
applicationConfig.php
416
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
CORRECT:
Somelibrary.php
Some_library.php
applicationconfig.php
application_config.php
Furthermore, class file names should match the name of the class itself. For example, if you have a class named
Myclass, then its filename must be Myclass.php.
Class and Method Naming
Class names should always start with an uppercase letter. Multiple words should be separated with an underscore, and
not CamelCased.
INCORRECT:
class superclass
class SuperClass
CORRECT:
class Super_class
class Super_class {
public function __construct()
{
}
}
Class methods should be entirely lowercased and named to clearly indicate their function, preferably including a verb.
Try to avoid overly long and verbose names. Multiple words should be separated with an underscore.
INCORRECT:
function
function
function
function
function
fileproperties()
// not descriptive and needs underscore separator
fileProperties()
// not descriptive and uses CamelCase
getfileproperties()
// Better! But still missing underscore separator
getFileProperties()
// uses CamelCase
get_the_file_properties_from_the_file()
// wordy
CORRECT:
function get_file_properties()
// descriptive, underscore separator, and all lowercase letters
Variable Names
The guidelines for variable naming are very similar to those used for class methods. Variables should contain only
lowercase letters, use underscore separators, and be reasonably named to indicate their purpose and contents. Very
short, non-word variables should only be used as iterators in for() loops.
INCORRECT:
10.12. General Topics
417
CodeIgniter Documentation, 3.0-dev
$j = ’foo’;
$Str
$bufferedText
$groupid
$name_of_last_city_used
//
//
//
//
//
single letter variables should only be used in for() loops
contains uppercase letters
uses CamelCasing, and could be shortened without losing semantic meaning
multiple words, needs underscore separator
too long
CORRECT:
for ($j = 0; $j < 10; $j++)
$str
$buffer
$group_id
$last_city
Commenting
In general, code should be commented prolifically. It not only helps describe the flow and intent of the code for less
experienced programmers, but can prove invaluable when returning to your own code months down the line. There is
not a required format for comments, but the following are recommended.
DocBlock style comments preceding class, method, and property declarations so they can be picked up by IDEs:
/**
* Super Class
*
Package Name
* @package
* @subpackage Subpackage
Category
* @category
Author Name
* @author
@link
http://example.com
*
*/
class Super_class {
/**
* Encodes string for use in XML
*
string $str
Input string
* @param
string
* @return
*/
function xml_encode($str)
/**
* Data for class manipulation
*
* @var array
*/
public $data = array();
Use single line comments within code, leaving a blank line between large comment blocks and code.
// break up the string by newlines
$parts = explode("\n", $str);
//
//
//
//
//
A longer comment that needs to give greater detail on what is
occurring and why can use multiple single-line comments. Try to
keep the width reasonable, around 70 characters is the easiest to
read. Don’t hesitate to link to permanent external resources
that may provide greater detail:
418
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
//
// http://example.com/information_about_something/in_particular/
$parts = $this->foo($parts);
Constants
Constants follow the same guidelines as do variables, except constants should always be fully uppercase. Always use
CodeIgniter constants when appropriate, i.e. SLASH, LD, RD, PATH_CACHE, etc.
INCORRECT:
myConstant
// missing underscore separator and not fully uppercase
N
// no single-letter constants
S_C_VER
// not descriptive
$str = str_replace(’{foo}’, ’bar’, $str);
// should use LD and RD constants
CORRECT:
MY_CONSTANT
NEWLINE
SUPER_CLASS_VERSION
$str = str_replace(LD.’foo’.RD, ’bar’, $str);
TRUE, FALSE, and NULL
TRUE, FALSE, and NULL keywords should always be fully uppercase.
INCORRECT:
if ($foo == true)
$bar = false;
function foo($bar = null)
CORRECT:
if ($foo == TRUE)
$bar = FALSE;
function foo($bar = NULL)
Logical Operators
Use of the || “or” comparison operator is discouraged, as its clarity on some output devices is low (looking like the
number 11, for instance). && is preferred over AND but either are acceptable, and a space should always precede and
follow !.
INCORRECT:
if
if
if
if
($foo || $bar)
($foo AND $bar) // okay but not recommended for common syntax highlighting applications
(!$foo)
(! is_array($foo))
CORRECT:
10.12. General Topics
419
CodeIgniter Documentation, 3.0-dev
if
if
if
if
($foo OR $bar)
($foo && $bar) // recommended
( ! $foo)
( ! is_array($foo))
Comparing Return Values and Typecasting
Some PHP functions return FALSE on failure, but may also have a valid return value of “” or 0, which would evaluate to FALSE in loose comparisons. Be explicit by comparing the variable type when using these return values in
conditionals to ensure the return value is indeed what you expect, and not a value that has an equivalent loose-type
evaluation.
Use the same stringency in returning and checking your own variables. Use === and !== as necessary.
INCORRECT:
// If ’foo’ is at the beginning of the string, strpos will return a 0,
// resulting in this conditional evaluating as TRUE
if (strpos($str, ’foo’) == FALSE)
CORRECT:
if (strpos($str, ’foo’) === FALSE)
INCORRECT:
function build_string($str = "")
{
if ($str == "") // uh-oh!
{
What if FALSE or the integer 0 is passed as an argument?
}
}
CORRECT:
function build_string($str = "")
{
if ($str === "")
{
}
}
See also information regarding typecasting, which can be quite useful. Typecasting has a slightly different effect
which may be desirable. When casting a variable as a string, for instance, NULL and boolean FALSE variables
become empty strings, 0 (and other numbers) become strings of digits, and boolean TRUE becomes “1”:
$str = (string) $str; // cast $str as a string
Debugging Code
Do not leave debugging code in your submissions, even when commented out. Things such as var_dump(),
print_r(), die()/exit() should not be included in your code unless it serves a specific purpose other than
debugging.
420
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Whitespace in Files
No whitespace can precede the opening PHP tag or follow the closing PHP tag. Output is buffered, so whitespace
in your files can cause output to begin before CodeIgniter outputs its content, leading to errors and an inability for
CodeIgniter to send proper headers.
Compatibility
CodeIgniter requires a minimum PHP version of 5.2.4. Your code must either be compatible with this minimum requirement, provide a suitable fallback, or be an optional feature that dies quietly without affecting a user’s application.
Additionally, do not use PHP functions that require non-default libraries to be installed unless your code contains an
alternative method when the function is not available.
One File per Class
Use separate files for each class, unless the classes are closely related. An example of a CodeIgniter file that contains
multiple classes is the Xmlrpc library file.
Whitespace
Use tabs for whitespace in your code, not spaces. This may seem like a small thing, but using tabs instead of whitespace
allows the developer looking at your code to have indentation at levels that they prefer and customize in whatever
application they use. And as a side benefit, it results in (slightly) more compact files, storing one tab character versus,
say, four space characters.
Line Breaks
Files must be saved with Unix line breaks. This is more of an issue for developers who work in Windows, but in any
case ensure that your text editor is setup to save files with Unix line breaks.
Code Indenting
Use Allman style indenting. With the exception of Class declarations, braces are always placed on a line by themselves,
and indented at the same level as the control statement that “owns” them.
INCORRECT:
function foo($bar) {
// ...
}
foreach ($arr as $key => $val) {
// ...
}
if ($foo == $bar) {
// ...
} else {
// ...
}
for ($i = 0; $i < 10; $i++)
10.12. General Topics
421
CodeIgniter Documentation, 3.0-dev
{
for ($j = 0; $j < 10; $j++)
{
// ...
}
}
try {
// ...
}
catch() {
// ...
}
CORRECT:
function foo($bar)
{
// ...
}
foreach ($arr as $key => $val)
{
// ...
}
if ($foo == $bar)
{
// ...
}
else
{
// ...
}
for ($i = 0; $i < 10; $i++)
{
for ($j = 0; $j < 10; $j++)
{
// ...
}
}
try
{
// ...
}
catch()
{
// ...
}
Bracket and Parenthetic Spacing
In general, parenthesis and brackets should not use any additional spaces. The exception is that a space should always
follow PHP control structures that accept arguments with parenthesis (declare, do-while, elseif, for, foreach, if, switch,
while), to help distinguish them from functions and increase readability.
422
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
INCORRECT:
$arr[ $foo ] = ’foo’;
CORRECT:
$arr[$foo] = ’foo’; // no spaces around array keys
INCORRECT:
function foo ( $bar )
{
}
CORRECT:
function foo($bar) // no spaces around parenthesis in function declarations
{
}
INCORRECT:
foreach( $query->result() as $row )
CORRECT:
foreach ($query->result() as $row) // single space following PHP control structures, but not in inter
Localized Text
CodeIgniter libraries should take advantage of corresponding language files whenever possible.
INCORRECT:
return "Invalid Selection";
CORRECT:
return $this->lang->line(’invalid_selection’);
Private Methods and Variables
Methods and variables that are only accessed internally, such as utility and helper functions that your public methods
use for code abstraction, should be prefixed with an underscore.
public function convert_text()
private function _convert_text()
PHP Errors
Code must run error free and not rely on warnings and notices to be hidden to meet this requirement. For instance,
never access a variable that you did not set yourself (such as $_POST array keys) without first checking to see that it
isset().
Make sure that your dev environment has error reporting enabled for ALL users, and that display_errors is enabled in
the PHP environment. You can check this setting with:
10.12. General Topics
423
CodeIgniter Documentation, 3.0-dev
if (ini_get(’display_errors’) == 1)
{
exit "Enabled";
}
On some servers where display_errors is disabled, and you do not have the ability to change this in the php.ini, you
can often enable it with:
ini_set(’display_errors’, 1);
: Setting the display_errors setting with ini_set() at runtime is not identical to having it enabled in the PHP
environment. Namely, it will not have any effect if the script has fatal errors.
Short Open Tags
Always use full PHP opening tags, in case a server does not have short_open_tag enabled.
INCORRECT:
<? echo $foo; ?>
<?=$foo?>
CORRECT:
<?php echo $foo; ?>
: PHP 5.4 will always have the <?= tag available.
One Statement Per Line
Never combine statements on one line.
INCORRECT:
$foo = ’this’; $bar = ’that’; $bat = str_replace($foo, $bar, $bag);
CORRECT:
$foo = ’this’;
$bar = ’that’;
$bat = str_replace($foo, $bar, $bag);
Strings
Always use single quoted strings unless you need variables parsed, and in cases where you do need variables parsed,
use braces to prevent greedy token parsing. You may also use double-quoted strings if the string contains single quotes,
so you do not have to use escape characters.
INCORRECT:
"My String"
"My string $foo"
’SELECT foo FROM bar WHERE baz = \’bag\’’
424
// no variable parsing, so no use for double quotes
// needs braces
// ugly
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
CORRECT:
’My String’
"My string {$foo}"
"SELECT foo FROM bar WHERE baz = ’bag’"
SQL Queries
SQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE, AS, JOIN, ON, IN, etc.
Break up long queries into multiple lines for legibility, preferably breaking for each clause.
INCORRECT:
// keywords are lowercase and query is too long for
// a single line (... indicates continuation of line)
$query = $this->db->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_
...where foo != ’oof’ and baz != ’zab’ order by foobaz limit 5, 100");
CORRECT:
$query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz
FROM exp_pre_email_addresses
WHERE foo != ’oof’
AND baz != ’zab’
ORDER BY foobaz
LIMIT 5, 100");
Default Function Arguments
Whenever appropriate, provide function argument defaults, which helps prevent PHP errors with mistaken calls and
provides common fallback values which can save a few lines of code. Example:
function foo($bar = ’’, $baz = FALSE)
10.13 Libraries
10.13.1 Benchmarking Class
CodeIgniter has a Benchmarking class that is always active, enabling the time difference between any two marked
points to be calculated.
: This class is initialized automatically by the system so there is no need to do it manually.
In addition, the benchmark is always started the moment the framework is invoked, and ended by the output class
right before sending the final view to the browser, enabling a very accurate timing of the entire system execution to be
shown.
10.13. Libraries
425
CodeIgniter Documentation, 3.0-dev
Table of Contents
• Benchmarking Class
– Using the Benchmark Class
– Profiling Your Benchmark Points
– Displaying Total Execution Time
– Displaying Memory Consumption
Using the Benchmark Class
The Benchmark class can be used within your controllers, views, or your models. The process for usage is this:
1. Mark a start point
2. Mark an end point
3. Run the “elapsed time” function to view the results
Here’s an example using real code:
$this->benchmark->mark(’code_start’);
// Some code happens here
$this->benchmark->mark(’code_end’);
echo $this->benchmark->elapsed_time(’code_start’, ’code_end’);
: The words “code_start” and “code_end” are arbitrary. They are simply words used to set two markers. You can use
any words you want, and you can set multiple sets of markers. Consider this example:
$this->benchmark->mark(’dog’);
// Some code happens here
$this->benchmark->mark(’cat’);
// More code happens here
$this->benchmark->mark(’bird’);
echo $this->benchmark->elapsed_time(’dog’, ’cat’);
echo $this->benchmark->elapsed_time(’cat’, ’bird’);
echo $this->benchmark->elapsed_time(’dog’, ’bird’);
Profiling Your Benchmark Points
If you want your benchmark data to be available to the Profiler all of your marked points must be set up in pairs,
and each mark point name must end with _start and _end. Each pair of points must otherwise be named identically.
Example:
$this->benchmark->mark(’my_mark_start’);
// Some code happens here...
426
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$this->benchmark->mark(’my_mark_end’);
$this->benchmark->mark(’another_mark_start’);
// Some more code happens here...
$this->benchmark->mark(’another_mark_end’);
Please read the Profiler page for more information.
Displaying Total Execution Time
If you would like to display the total elapsed time from the moment CodeIgniter starts to the moment the final output
is sent to the browser, simply place this in one of your view templates:
<?php echo $this->benchmark->elapsed_time();?>
You’ll notice that it’s the same function used in the examples above to calculate the time between two point, except
you are not using any parameters. When the parameters are absent, CodeIgniter does not stop the benchmark until
right before the final output is sent to the browser. It doesn’t matter where you use the function call, the timer will
continue to run until the very end.
An alternate way to show your elapsed time in your view files is to use this pseudo-variable, if you prefer not to use
the pure PHP:
{elapsed_time}
: If you want to benchmark anything within your controller functions you must set your own start/end points.
Displaying Memory Consumption
If your PHP installation is configured with –enable-memory-limit, you can display the amount of memory consumed
by the entire system using the following code in one of your view file:
<?php echo $this->benchmark->memory_usage();?>
: This function can only be used in your view files. The consumption will reflect the total memory used by the entire
app.
An alternate way to show your memory usage in your view files is to use this pseudo-variable, if you prefer not to use
the pure PHP:
{memory_usage}
10.13.2 Caching Driver
CodeIgniter features wrappers around some of the most popular forms of fast and dynamic caching. All but file-based
caching require specific server requirements, and a Fatal Exception will be thrown if server requirements are not met.
10.13. Libraries
427
CodeIgniter Documentation, 3.0-dev
Table of Contents
• Caching Driver
– Example Usage
– Function Reference
* is_supported()
* get()
* save()
* delete()
* clean()
* cache_info()
* get_metadata()
– Drivers
* Alternative PHP Cache (APC) Caching
* File-based Caching
* Memcached Caching
* WinCache Caching
* Redis Caching
* Dummy Cache
Example Usage
The following example will load the cache driver, specify APC as the driver to use, and fall back to file-based caching
if APC is not available in the hosting environment.
$this->load->driver(’cache’, array(’adapter’ => ’apc’, ’backup’ => ’file’));
if ( ! $foo = $this->cache->get(’foo’))
{
echo ’Saving to the cache!<br />’;
$foo = ’foobarbaz!’;
// Save into the cache for 5 minutes
$this->cache->save(’foo’, $foo, 300);
}
echo $foo;
You can also prefix cache item names via the key_prefix setting, which is useful to avoid collisions when you’re
running multiple applications on the same environment.
$this->load->driver(’cache’,
array(’adapter’ => ’apc’, ’backup’ => ’file’, ’key_prefix’ => ’my_’)
);
$this->cache->get(’foo’); // Will get the cache entry named ’my_foo’
Function Reference
class CI_Cache
428
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
is_supported()
CI_Cache::is_supported($driver)
This function is automatically called when accessing drivers via $this->cache->get(). However, if
the individual drivers are used, make sure to call this function to ensure the driver is supported in the
hosting environment.
• $driver (string) – the name of the caching driver
TRUE if supported, FALSE if not
Boolean
if ($this->cache->apc->is_supported()
{
if ($data = $this->cache->apc->get(’my_cache’))
{
// do things.
}
}
get()
CI_Cache::get($id)
This function will attempt to fetch an item from the cache store. If the item does not exist, the
function will return FALSE.
• $id (string) – name of cached item
The item if it exists, FALSE if it does not
Mixed
$foo = $this->cache->get(’my_cached_item’);
save()
CI_Cache::save($id, $data[, $ttl ])
This function will save an item to the cache store. If saving fails, the function will return FALSE.
• $id (string) – name of the cached item
• $data (mixed) – the data to save
• $ttl (int) – Time To Live, in seconds (default 60)
TRUE on success, FALSE on failure
Boolean
$this->cache->save(’cache_item_id’, ’data_to_cache’);
10.13. Libraries
429
CodeIgniter Documentation, 3.0-dev
delete()
CI_Cache::delete($id)
This function will delete a specific item from the cache store. If item deletion fails, the function will
return FALSE.
• $id (string) – name of cached item
TRUE if deleted, FALSE if the deletion fails
Boolean
$this->cache->delete(’cache_item_id’);
clean()
CI_Cache::clean()
This function will ‘clean’ the entire cache. If the deletion of the cache files fails, the function will
return FALSE.
TRUE if deleted, FALSE if the deletion fails
Boolean
$this->cache->clean();
cache_info()
CI_Cache::cache_info()
This function will return information on the entire cache.
information on the entire cache
Mixed
var_dump($this->cache->cache_info());
: The information returned and the structure of the data is dependent on which adapter is being
used.
get_metadata()
CI_Cache::get_metadata($id)
This function will return detailed information on a specific item in the cache.
• $id (string) – name of cached item
metadadta for the cached item
Mixed
var_dump($this->cache->get_metadata(’my_cached_item’));
430
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
: The information returned and the structure of the data is dependent on which adapter is being
used.
Drivers
Alternative PHP Cache (APC) Caching
All of the functions listed above can be accessed without passing a specific adapter to the driver loader as follows:
$this->load->driver(’cache’);
$this->cache->apc->save(’foo’, ’bar’, 10);
For more information on APC, please see http://php.net/apc.
File-based Caching
Unlike caching from the Output Class, the driver file-based caching allows for pieces of view files to be cached. Use
this with care, and make sure to benchmark your application, as a point can come where disk I/O will negate positive
gains by caching.
All of the functions listed above can be accessed without passing a specific adapter to the driver loader as follows:
$this->load->driver(’cache’);
$this->cache->file->save(’foo’, ’bar’, 10);
Memcached Caching
Multiple Memcached servers can be specified in the memcached.php configuration file, located in the _application/config/* directory.
All of the methods listed above can be accessed without passing a specific adapter to the driver loader as follows:
$this->load->driver(’cache’);
$this->cache->memcached->save(’foo’, ’bar’, 10);
For more information on Memcached, please see http://php.net/memcached.
WinCache Caching
Under Windows, you can also utilize the WinCache driver.
All of the functions listed above can be accessed without passing a specific adapter to the driver loader as follows:
$this->load->driver(’cache’);
$this->cache->wincache->save(’foo’, ’bar’, 10);
For more information on WinCache, please see http://php.net/wincache.
10.13. Libraries
431
CodeIgniter Documentation, 3.0-dev
Redis Caching
Redis is an in-memory key-value store which can operate in LRU cache mode. To use it, you need Redis server and
phpredis PHP extension https://github.com/nicolasff/phpredis.
Config options to connect to redis server must be stored in the application/config/redis.php file. Available options are:
$config[’socket_type’] = ’tcp’; //‘tcp‘ or ‘unix‘
$config[’socket’] = ’/var/run/redis.sock’; // in case of ‘unix‘ socket type
$config[’host’] = ’127.0.0.1’;
$config[’password’] = NULL;
$config[’port’] = 6379;
$config[’timeout’] = 0;
All of the methods listed above can be accessed without passing a specific adapter to the driver loader as follows:
$this->load->driver(’cache’);
$this->cache->redis->save(’foo’, ’bar’, 10);
For more information on Redis, please see http://redis.io.
Dummy Cache
This is a caching backend that will always ‘miss.’ It stores no data, but lets you keep your caching code in place in
environments that don’t support your chosen cache.
10.13.3 Calendaring Class
The Calendar class enables you to dynamically create calendars. Your calendars can be formatted through the use of
a calendar template, allowing 100% control over every aspect of its design. In addition, you can pass data to your
calendar cells.
Initializing the Class
Like most other classes in CodeIgniter, the Calendar class is initialized in your controller using the $this->load->library
function:
$this->load->library(’calendar’);
Once loaded, the Calendar object will be available using:
$this->calendar
Displaying a Calendar
Here is a very simple example showing how you can display a calendar:
$this->load->library(’calendar’);
echo $this->calendar->generate();
The above code will generate a calendar for the current month/year based on your server time. To show a calendar for
a specific month and year you will pass this information to the calendar generating function:
432
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$this->load->library(’calendar’);
echo $this->calendar->generate(2006, 6);
The above code will generate a calendar showing the month of June in 2006. The first parameter specifies the year,
the second parameter specifies the month.
Passing Data to your Calendar Cells
To add data to your calendar cells involves creating an associative array in which the keys correspond to the days
you wish to populate and the array value contains the data. The array is passed to the third parameter of the calendar
generating function. Consider this example:
$this->load->library(’calendar’);
$data = array(
3
7
13
26
);
=>
=>
=>
=>
’http://example.com/news/article/2006/03/’,
’http://example.com/news/article/2006/07/’,
’http://example.com/news/article/2006/13/’,
’http://example.com/news/article/2006/26/’
echo $this->calendar->generate(2006, 6, $data);
Using the above example, day numbers 3, 7, 13, and 26 will become links pointing to the URLs you’ve provided.
: By default it is assumed that your array will contain links. In the section that explains the calendar template
below you’ll see how you can customize how data passed to your cells is handled so you can pass different types of
information.
Setting Display Preferences
There are seven preferences you can set to control various aspects of the calendar. Preferences are set by passing an
array of preferences in the second parameter of the loading function. Here is an example:
$prefs = array (
’start_day’
’month_type’
’day_type’
);
=> ’saturday’,
=> ’long’,
=> ’short’
$this->load->library(’calendar’, $prefs);
echo $this->calendar->generate();
The above code would start the calendar on saturday, use the “long” month heading, and the “short” day names. More
information regarding preferences below.
10.13. Libraries
433
CodeIgniter Documentation, 3.0-dev
Preference
template
De- Options
fault
None None
Description
lotime() None
cal_time
start_day sun- Any week day (sunday,
day
monday, tuesday, etc.)
month_typelong long, short
day_type
abr
long, short, abr
show_next_prev
FALSETRUE/FALSE (boolean)
next_prev_url
None A URL
A string containing your calendar template. See the template
section below.
A Unix timestamp corresponding to the current time.
Sets the day of the week the calendar should start on.
Determines what version of the month name to use in the header.
long = January, short = Jan.
Determines what version of the weekday names to use in the
column headers. long = Sunday, short = Sun, abr = Su.
Determines whether to display links allowing you to toggle to
next/previous months. See information on this feature below.
Sets the basepath used in the next/previous calendar links.
Showing Next/Previous Month Links
To allow your calendar to dynamically increment/decrement via the next/previous links requires that you set up your
calendar code similar to this example:
$prefs = array (
’show_next_prev’
’next_prev_url’
);
=> TRUE,
=> ’http://example.com/index.php/calendar/show/’
$this->load->library(’calendar’, $prefs);
echo $this->calendar->generate($this->uri->segment(3), $this->uri->segment(4));
You’ll notice a few things about the above example:
• You must set the “show_next_prev” to TRUE.
• You must supply the URL to the controller containing your calendar in the “next_prev_url” preference.
• You must supply the “year” and “month” to the calendar generating function via the URI segments where they
appear (Note: The calendar class automatically adds the year/month to the base URL you provide.).
Creating a Calendar Template
By creating a calendar template you have 100% control over the design of your calendar. Each component of your
calendar will be placed within a pair of pseudo-variables as shown here:
$prefs[’template’] = ’
{table_open}<table border="0" cellpadding="0" cellspacing="0">{/table_open}
{heading_row_start}<tr>{/heading_row_start}
{heading_previous_cell}<th><a href="{previous_url}">&lt;&lt;</a></th>{/heading_previous_cell}
{heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell}
{heading_next_cell}<th><a href="{next_url}">&gt;&gt;</a></th>{/heading_next_cell}
{heading_row_end}</tr>{/heading_row_end}
434
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
{week_row_start}<tr>{/week_row_start}
{week_day_cell}<td>{week_day}</td>{/week_day_cell}
{week_row_end}</tr>{/week_row_end}
{cal_row_start}<tr>{/cal_row_start}
{cal_cell_start}<td>{/cal_cell_start}
{cal_cell_content}<a href="{content}">{day}</a>{/cal_cell_content}
{cal_cell_content_today}<div class="highlight"><a href="{content}">{day}</a></div>{/cal_cell_conte
{cal_cell_no_content}{day}{/cal_cell_no_content}
{cal_cell_no_content_today}<div class="highlight">{day}</div>{/cal_cell_no_content_today}
{cal_cell_blank}&nbsp;{/cal_cell_blank}
{cal_cell_end}</td>{/cal_cell_end}
{cal_row_end}</tr>{/cal_row_end}
{table_close}</table>{/table_close}
’;
$this->load->library(’calendar’, $prefs);
echo $this->calendar->generate();
10.13.4 Shopping Cart Class
The Cart Class permits items to be added to a session that stays active while a user is browsing your site. These items
can be retrieved and displayed in a standard “shopping cart” format, allowing the user to update the quantity or remove
items from the cart.
Please note that the Cart Class ONLY provides the core “cart” functionality. It does not provide shipping, credit card
authorization, or other processing components.
Page Contents
• Shopping Cart Class
– Initializing the Shopping Cart Class
– Adding an Item to The Cart
– Adding Multiple Items to The Cart
– Displaying the Cart
– Updating The Cart
* What is a Row ID?
– Function Reference
* $this->cart->insert();
* $this->cart->update();
* $this->cart->remove(rowid);
* $this->cart->total();
* $this->cart->total_items();
* $this->cart->contents(boolean);
* $this->cart->get_item($row_id);
* $this->cart->has_options($row_id);
* $this->cart->product_options($row_id);
* $this->cart->destroy();
10.13. Libraries
435
CodeIgniter Documentation, 3.0-dev
Initializing the Shopping Cart Class
: The Cart class utilizes CodeIgniter’s Session Class to save the cart information to a database, so before using the
Cart class you must set up a database table as indicated in the Session Documentation, and set the session preferences
in your application/config/config.php file to utilize a database.
To initialize the Shopping Cart Class in your controller constructor, use the $this->load->library function:
$this->load->library(’cart’);
Once loaded, the Cart object will be available using:
$this->cart
: The Cart Class will load and initialize the Session Class automatically, so unless you are using sessions elsewhere
in your application, you do not need to load the Session class.
Adding an Item to The Cart
To add an item to the shopping cart, simply pass an array with the product information to the $this->cart->insert()
function, as shown below:
$data = array(
’id’
’qty’
’price’
’name’
’options’
=>
=>
=>
=>
=>
’sku_123ABC’,
1,
39.95,
’T-Shirt’,
array(’Size’ => ’L’, ’Color’ => ’Red’)
);
$this->cart->insert($data);
: The first four array indexes above (id, qty, price, and name) are required. If you omit any of them the data will not
be saved to the cart. The fifth index (options) is optional. It is intended to be used in cases where your product has
options associated with it. Use an array for options, as shown above.
The five reserved indexes are:
• id - Each product in your store must have a unique identifier. Typically this will be an “sku” or other such
identifier.
• qty - The quantity being purchased.
• price - The price of the item.
• name - The name of the item.
• options - Any additional attributes that are needed to identify the product. These must be passed via an array.
In addition to the five indexes above, there are two reserved words: rowid and subtotal. These are used internally by
the Cart class, so please do NOT use those words as index names when inserting data into the cart.
Your array may contain additional data. Anything you include in your array will be stored in the session. However, it
is best to standardize your data among all your products in order to make displaying the information in a table easier.
The insert() method will return the $rowid if you successfully insert a single item.
436
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Adding Multiple Items to The Cart
By using a multi-dimensional array, as shown below, it is possible to add multiple products to the cart in one action.
This is useful in cases where you wish to allow people to select from among several items on the same page.
$data = array(
array(
’id’
’qty’
’price’
’name’
’options’
=>
=>
=>
=>
=>
’sku_123ABC’,
1,
39.95,
’T-Shirt’,
array(’Size’ => ’L’, ’Color’ => ’Red’)
’id’
’qty’
’price’
’name’
=>
=>
=>
=>
’sku_567ZYX’,
1,
9.95,
’Coffee Mug’
’id’
’qty’
’price’
’name’
=>
=>
=>
=>
’sku_965QRS’,
1,
29.95,
’Shot Glass’
),
array(
),
array(
)
);
$this->cart->insert($data);
Displaying the Cart
To display the cart you will create a view file with code similar to the one shown below.
Please note that this example uses the form helper.
<?php echo form_open(’path/to/controller/update/function’); ?>
<table cellpadding="6" cellspacing="1" style="width:100%" border="0">
<tr>
<th>QTY</th>
<th>Item Description</th>
<th style="text-align:right">Item Price</th>
<th style="text-align:right">Sub-Total</th>
</tr>
<?php $i = 1; ?>
<?php foreach ($this->cart->contents() as $items): ?>
<?php echo form_hidden($i.’[rowid]’, $items[’rowid’]); ?>
<tr>
<td><?php echo form_input(array(’name’ => $i.’[qty]’, ’value’ => $items[’qty’], ’maxlength’
<td>
<?php echo $items[’name’]; ?>
<?php if ($this->cart->has_options($items[’rowid’]) == TRUE): ?>
10.13. Libraries
437
CodeIgniter Documentation, 3.0-dev
<p>
<?php foreach ($this->cart->product_options($items[’rowid’])
<strong><?php echo $option_name; ?>:</strong> <?php e
<?php endforeach; ?>
</p>
<?php endif; ?>
</td>
<td style="text-align:right"><?php echo $this->cart->format_number($items[’price’]); ?></td
<td style="text-align:right">$<?php echo $this->cart->format_number($items[’subtotal’]); ?>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
<tr>
<td colspan="2"> </td>
<td class="right"><strong>Total</strong></td>
<td class="right">$<?php echo $this->cart->format_number($this->cart->total()); ?></td>
</tr>
</table>
<p><?php echo form_submit(’’, ’Update your Cart’); ?></p>
Updating The Cart
To update the information in your cart, you must pass an array containing the Row ID and quantity to the $this->cart>update() function:
: If the quantity is set to zero, the item will be removed from the cart.
$data = array(
’rowid’ => ’b99ccdf16028f015540f341130b6d8ec’,
’qty’
=> 3
);
$this->cart->update($data);
// Or a multi-dimensional array
$data = array(
array(
’rowid’
’qty’
=> ’b99ccdf16028f015540f341130b6d8ec’,
=> 3
’rowid’
’qty’
=> ’xw82g9q3r495893iajdh473990rikw23’,
=> 4
’rowid’
=> ’fh4kdkkkaoe30njgoe92rkdkkobec333’,
),
array(
),
array(
438
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
’qty’
=> 2
)
);
$this->cart->update($data);
What is a Row ID?
The row ID is a unique identifier that is generated by the cart code when an item is added to the cart. The reason a
unique ID is created is so that identical products with different options can be managed by the cart.
For example, let’s say someone buys two identical t-shirts (same product ID), but in different sizes. The product ID
(and other attributes) will be identical for both sizes because it’s the same shirt. The only difference will be the size.
The cart must therefore have a means of identifying this difference so that the two sizes of shirts can be managed
independently. It does so by creating a unique “row ID” based on the product ID and any options associated with it.
In nearly all cases, updating the cart will be something the user does via the “view cart” page, so as a developer, it is
unlikely that you will ever have to concern yourself with the “row ID”, other then making sure your “view cart” page
contains this information in a hidden form field, and making sure it gets passed to the update function when the update
form is submitted. Please examine the construction of the “view cart” page above for more information.
Function Reference
$this->cart->insert();
Permits you to add items to the shopping cart, as outlined above.
$this->cart->update();
Permits you to update items in the shopping cart, as outlined above.
$this->cart->remove(rowid);
Allows you to remove an item from the shopping cart by passing it the rowid.
$this->cart->total();
Displays the total amount in the cart.
$this->cart->total_items();
Displays the total number of items in the cart.
$this->cart->contents(boolean);
Returns an array containing everything in the cart. You can sort the order, by which this is returned by passing it “true”
where the contents will be sorted from newest to oldest, by leaving this function blank, you’ll automatically just get
first added to the basket to last added to the basket.
10.13. Libraries
439
CodeIgniter Documentation, 3.0-dev
$this->cart->get_item($row_id);
Returns an array containing data for the item matching the specified row ID, or FALSE if no such item exists.
$this->cart->has_options($row_id);
Returns TRUE (boolean) if a particular row in the cart contains options. This function is designed to be used in a
loop with $this->cart->contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart
example above.
$this->cart->product_options($row_id);
Returns an array of options for a particular product. This function is designed to be used in a loop with $this->cart>contents(), since you must pass the rowid to this function, as shown in the Displaying the Cart example above.
$this->cart->destroy();
Permits you to destroy the cart. This function will likely be called when you are finished processing the customer’s
order.
10.13.5 Config Class
The Config class provides a means to retrieve configuration preferences. These preferences can come from the default
config file (application/config/config.php) or from your own custom config files.
: This class is initialized automatically by the system so there is no need to do it manually.
Page Contents
• Config Class
– Anatomy of a Config File
– Loading a Config File
* Manual Loading
* Auto-loading
– Fetching Config Items
– Setting a Config Item
– Environments
– Helper Functions
* $this->config->site_url();
* $this->config->base_url();
* $this->config->system_url();
Anatomy of a Config File
By default, CodeIgniter has one primary config file, located at application/config/config.php. If you open the file using
your text editor you’ll see that config items are stored in an array called $config.
440
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
You can add your own config items to this file, or if you prefer to keep your configuration items separate (assuming
you even need config items), simply create your own file and save it in config folder.
: If you do create your own config files use the same format as the primary one, storing your items in an array called
$config. CodeIgniter will intelligently manage these files so there will be no conflict even though the array has the
same name (assuming an array index is not named the same as another).
Loading a Config File
: CodeIgniter automatically loads the primary config file (application/config/config.php), so you will only need to
load a config file if you have created your own.
There are two ways to load a config file:
Manual Loading
To load one of your custom config files you will use the following function within the controller that needs it:
$this->config->load(’filename’);
Where filename is the name of your config file, without the .php file extension.
If you need to load multiple config files normally they will be merged into one master config array. Name collisions
can occur, however, if you have identically named array indexes in different config files. To avoid collisions you can
set the second parameter to TRUE and each config file will be stored in an array index corresponding to the name of
the config file. Example:
// Stored in an array with this prototype: $this->config[’blog_settings’] = $config
$this->config->load(’blog_settings’, TRUE);
Please see the section entitled Fetching Config Items below to learn how to retrieve config items set this way.
The third parameter allows you to suppress errors in the event that a config file does not exist:
$this->config->load(’blog_settings’, FALSE, TRUE);
Auto-loading
If you find that you need a particular config file globally, you can have it loaded automatically by the system. To do
this, open the autoload.php file, located at application/config/autoload.php, and add your config file as indicated in
the file.
Fetching Config Items
To retrieve an item from your config file, use the following function:
$this->config->item(’item name’);
Where item name is the $config array index you want to retrieve. For example, to fetch your language choice you’ll
do this:
10.13. Libraries
441
CodeIgniter Documentation, 3.0-dev
$lang = $this->config->item(’language’);
The function returns NULL if the item you are trying to fetch does not exist.
If you are using the second parameter of the $this->config->load function in order to assign your config items to a
specific index you can retrieve it by specifying the index name in the second parameter of the $this->config->item()
function. Example:
// Loads a config file named blog_settings.php and assigns it to an index named "blog_settings"
$this->config->load(’blog_settings’, TRUE);
// Retrieve a config item named site_name contained within the blog_settings array
$site_name = $this->config->item(’site_name’, ’blog_settings’);
// An alternate way to specify the same item:
$blog_config = $this->config->item(’blog_settings’);
$site_name = $blog_config[’site_name’];
Setting a Config Item
If you would like to dynamically set a config item or change an existing one, you can do so using:
$this->config->set_item(’item_name’, ’item_value’);
Where item_name is the $config array index you want to change, and item_value is its value.
Environments
You may load different configuration files depending on the current environment. The ENVIRONMENT constant is
defined in index.php, and is described in detail in the Handling Environments section.
To create an environment-specific configuration file, create or copy a configuration file in application/config/{ENVIRONMENT}/{FILENAME}.php
For example, to create a production-only config.php, you would:
1. Create the directory application/config/production/
2. Copy your existing config.php into the above directory
3. Edit application/config/production/config.php so it contains your production settings
When you set the ENVIRONMENT constant to ‘production’, the settings for your new production-only config.php
will be loaded.
You can place the following configuration files in environment-specific folders:
• Default CodeIgniter configuration files
• Your own custom configuration files
: CodeIgniter always loads the global config file first (i.e., the one in application/config/), then tries to load the
configuration files for the current environment. This means you are not obligated to place all of your configuration
files in an environment folder. Only the files that change per environment. Additionally you don’t have to copy all the
config items in the environment config file. Only the config items that you wish to change for your environment. The
config items declared in your environment folders always overwrite those in your global config files.
442
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Helper Functions
The config class has the following helper functions:
$this->config->site_url();
This function retrieves the URL to your site, along with the “index” value you’ve specified in the config file.
$this->config->base_url();
This function retrieves the URL to your site, plus an optional path such as to a stylesheet or image.
The two functions above are normally accessed via the corresponding functions in the URL Helper.
$this->config->system_url();
This function retrieves the URL to your system folder.
10.13.6 Email Class
CodeIgniter’s robust Email Class supports the following features:
• Multiple Protocols: Mail, Sendmail, and SMTP
• TLS and SSL Encryption for SMTP
• Multiple recipients
• CC and BCCs
• HTML or Plaintext email
• Attachments
• Word wrapping
• Priorities
• BCC Batch Mode, enabling large email lists to be broken into small BCC batches.
• Email Debugging tools
Sending Email
Sending email is not only simple, but you can configure it on the fly or set your preferences in a config file.
Here is a basic example demonstrating how you might send email. Note: This example assumes you are sending the
email from one of your controllers.
$this->load->library(’email’);
$this->email->from(’your@example.com’, ’Your Name’);
$this->email->to(’someone@example.com’);
$this->email->cc(’another@another-example.com’);
$this->email->bcc(’them@their-example.com’);
10.13. Libraries
443
CodeIgniter Documentation, 3.0-dev
$this->email->subject(’Email Test’);
$this->email->message(’Testing the email class.’);
$this->email->send();
Setting Email Preferences
There are 21 different preferences available to tailor how your email messages are sent. You can either set them
manually as described here, or automatically via preferences stored in your config file, described below:
Preferences are set by passing an array of preference values to the email initialize method. Here is an example of how
you might set some preferences:
$config[’protocol’] = ’sendmail’;
$config[’mailpath’] = ’/usr/sbin/sendmail’;
$config[’charset’] = ’iso-8859-1’;
$config[’wordwrap’] = TRUE;
$this->email->initialize($config);
: Most of the preferences have default values that will be used if you do not set them.
Setting Email Preferences in a Config File
If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create
a new file called the email.php, add the $config array in that file. Then save the file at config/email.php and it will
be used automatically. You will NOT need to use the $this->email->initialize() method if you save your
preferences in a config file.
Email Preferences
The following is a list of all the preferences that can be set when sending email.
444
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Preference
useragent
protocol
Default
Value
CodeIgniter
None
The “user agent”.
mail,
sendmail,
or smtp
/usr/sbin/sendmail
None
smtp_crypto
No Default
wordTRUE
wrap
wrapchars76
mailtype text
priority
crlf
Description
mail
mailpath
smtp_hostNo Default
smtp_userNo Default
smtp_passNo Default
smtp_port25
smtp_timeout
5
smtp_keepalive
FALSE
charset
validate
Options
None
None
None
None
None
TRUE or
FALSE
(boolean)
tls or ssl
TRUE or
FALSE
(boolean)
text or html
$config[’charset’]
FALSE
TRUE or
FALSE
(boolean)
3
1, 2, 3, 4, 5
\n
new\n
line
bcc_batch_mode
FALSE
bcc_batch_size
200
dsn
FALSE
“\r\n” or
“\n” or “\r”
“\r\n” or
“\n” or “\r”
TRUE or
FALSE
(boolean)
None
TRUE or
FALSE
(boolean)
The mail sending protocol.
The server path to Sendmail.
SMTP Server Address.
SMTP Username.
SMTP Password.
SMTP Port.
SMTP Timeout (in seconds).
Enable persistent SMTP connections.
SMTP Encryption
Enable word-wrap.
Character count to wrap at.
Type of mail. If you send HTML email you must send it as a complete
web page. Make sure you don’t have any relative links or relative image
paths otherwise they will not work.
Character set (utf-8, iso-8859-1, etc.).
Whether to validate the email address.
Email Priority. 1 = highest. 5 = lowest. 3 = normal.
Newline character. (Use “\r\n” to comply with RFC 822).
Newline character. (Use “\r\n” to comply with RFC 822).
Enable BCC Batch Mode.
Number of emails in each BCC batch.
Enable notify message from server
Email Methods Reference
$this->email->from()
Sets the email address and name of the person sending the email:
$this->email->from(’you@example.com’, ’Your Name’);
You can also set a Return-Path, to help redirect undelivered mail:
10.13. Libraries
445
CodeIgniter Documentation, 3.0-dev
$this->email->from(’you@example.com’, ’Your Name’, ’returned_emails@example.com’);
: Return-Path can’t be used if you’ve configured ‘smtp’ as your protocol.
$this->email->reply_to()
Sets the reply-to address. If the information is not provided the information in the “from” method is used. Example:
$this->email->reply_to(’you@example.com’, ’Your Name’);
$this->email->to()
Sets the email address(s) of the recipient(s). Can be a single email, a comma-delimited list or an array:
$this->email->to(’someone@example.com’);
$this->email->to(’one@example.com, two@example.com, three@example.com’);
$list = array(’one@example.com’, ’two@example.com’, ’three@example.com’);
$this->email->to($list);
$this->email->cc()
Sets the CC email address(s). Just like the “to”, can be a single email, a comma-delimited list or an array.
$this->email->bcc()
Sets the BCC email address(s). Just like the “to”, can be a single email, a comma-delimited list or an array.
$this->email->subject()
Sets the email subject:
$this->email->subject(’This is my subject’);
$this->email->message()
Sets the email message body:
$this->email->message(’This is my message’);
$this->email->set_alt_message()
Sets the alternative email message body:
446
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$this->email->set_alt_message(’This is the alternative message’);
This is an optional message string which can be used if you send HTML formatted email. It lets you specify an
alternative message with no HTML formatting which is added to the header string for people who do not accept
HTML email. If you do not set your own message CodeIgniter will extract the message from your HTML email and
strip the tags.
$this->email->set_header()
Appends additional headers to the e-mail:
$this->email->set_header(’Header1’, ’Value1’);
$this->email->set_header(’Header2’, ’Value2’);
$this->email->clear()
Initializes all the email variables to an empty state. This method is intended for use if you run the email sending
method in a loop, permitting the data to be reset between cycles.
foreach ($list as $name => $address)
{
$this->email->clear();
$this->email->to($address);
$this->email->from(’your@example.com’);
$this->email->subject(’Here is your info ’.$name);
$this->email->message(’Hi ’.$name.’ Here is the info you requested.’);
$this->email->send();
}
If you set the parameter to TRUE any attachments will be cleared as well:
$this->email->clear(TRUE);
$this->email->send()
The Email sending method. Returns boolean TRUE or FALSE based on success or failure, enabling it to be used
conditionally:
if ( ! $this->email->send())
{
// Generate error
}
This method will automatically clear all parameters if the request was successful. To stop this behaviour pass FALSE:
if ($this->email->send(FALSE))
{
// Parameters won’t be cleared
}
: In order to use the print_debugger() method, you need to avoid clearing the email parameters.
10.13. Libraries
447
CodeIgniter Documentation, 3.0-dev
$this->email->attach()
Enables you to send an attachment. Put the file path/name in the first parameter. Note: Use a file path, not a URL. For
multiple attachments use the method multiple times. For example:
$this->email->attach(’/path/to/photo1.jpg’);
$this->email->attach(’/path/to/photo2.jpg’);
$this->email->attach(’/path/to/photo3.jpg’);
To use the default disposition (attachment), leave the second parameter blank, otherwise use a custom disposition:
$this->email->attach(’image.jpg’, ’inline’);
If you’d like to use a custom file name, you can use the third paramater:
$this->email->attach(’filename.pdf’, ’attachment’, ’report.pdf’);
If you need to use a buffer string instead of a real - physical - file you can use the first parameter as buffer, the third
parameter as file name and the fourth parameter as mime-type:
$this->email->attach($buffer, ’attachment’, ’report.pdf’, ’application/pdf’);
$this->email->print_debugger()
Returns a string containing any server messages, the email headers, and the email messsage. Useful for debugging.
You can optionally specify which parts of the message should be printed. Valid options are: headers, subject, body.
Example:
// You need to pass FALSE while sending in order for the email data
// to not be cleared - if that happens, print_debugger() would have
// nothing to output.
$this->email->send(FALSE);
// Will only print the email headers, excluding the message subject and body
$this->email->print_debugger(array(’headers’));
: By default, all of the raw data will be printed.
Overriding Word Wrapping
If you have word wrapping enabled (recommended to comply with RFC 822) and you have a very long link in your
email it can get wrapped too, causing it to become un-clickable by the person receiving it. CodeIgniter lets you
manually override word wrapping within part of your message like this:
The text of your email that
gets wrapped normally.
{unwrap}http://example.com/a_long_link_that_should_not_be_wrapped.html{/unwrap}
More text that will be
wrapped normally.
Place the item you do not want word-wrapped between: {unwrap} {/unwrap}
448
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
10.13.7 Encryption Class
The Encryption Class provides two-way data encryption. It uses a scheme that either compiles the message using a
randomly hashed bitwise XOR encoding scheme, or is encrypted using the Mcrypt library. If Mcrypt is not available
on your server the encoded message will still provide a reasonable degree of security for encrypted sessions or other
such “light” purposes. If Mcrypt is available, you’ll be provided with a high degree of security appropriate for storage.
Setting your Key
A key is a piece of information that controls the cryptographic process and permits an encrypted string to be decoded.
In fact, the key you chose will provide the only means to decode data that was encrypted with that key, so not only
must you choose the key carefully, you must never change it if you intend use it for persistent data.
It goes without saying that you should guard your key carefully. Should someone gain access to your key, the data will
be easily decoded. If your server is not totally under your control it’s impossible to ensure key security so you may
want to think carefully before using it for anything that requires high security, like storing credit card numbers.
To take maximum advantage of the encryption algorithm, your key should be 32 characters in length (256 bits). The
key should be as random a string as you can concoct, with numbers and uppercase and lowercase letters. Your key
should not be a simple text string. In order to be cryptographically secure it needs to be as random as possible.
Your key can be either stored in your application/config/config.php, or you can design your own storage mechanism
and pass the key dynamically when encoding/decoding.
To save your key to your application/config/config.php, open the file and set:
$config[’encryption_key’] = "YOUR KEY";
Message Length
It’s important for you to know that the encoded messages the encryption function generates will be approximately 2.6
times longer than the original message. For example, if you encrypt the string “my super secret data”, which is 21
characters in length, you’ll end up with an encoded string that is roughly 55 characters (we say “roughly” because the
encoded string length increments in 64 bit clusters, so it’s not exactly linear). Keep this information in mind when
selecting your data storage mechanism. Cookies, for example, can only hold 4K of information.
Initializing the Class
Like most other classes in CodeIgniter, the Encryption class is initialized in your controller using the $this->load>library function:
$this->load->library(’encrypt’);
Once loaded, the Encrypt library object will be available using: $this->encrypt
$this->encrypt->encode()
Performs the data encryption and returns it as a string. Example:
$msg = ’My secret message’;
$encrypted_string = $this->encrypt->encode($msg);
10.13. Libraries
449
CodeIgniter Documentation, 3.0-dev
You can optionally pass your encryption key via the second parameter if you don’t want to use the one in your config
file:
$msg = ’My secret message’;
$key = ’super-secret-key’;
$encrypted_string = $this->encrypt->encode($msg, $key);
$this->encrypt->decode()
Decrypts an encoded string. Example:
$encrypted_string = ’APANtByIGI1BpVXZTJgcsAG8GZl8pdwwa84’;
$plaintext_string = $this->encrypt->decode($encrypted_string);
You can optionally pass your encryption key via the second parameter if you don’t want to use the one in your config
file:
$msg = ’My secret message’;
$key = ’super-secret-key’;
$encrypted_string = $this->encrypt->decode($msg, $key);
$this->encrypt->set_cipher();
Permits you to set an Mcrypt cipher. By default it uses MCRYPT_RIJNDAEL_256. Example:
$this->encrypt->set_cipher(MCRYPT_BLOWFISH);
Please visit php.net for a list of available ciphers.
If you’d like to manually test whether your server supports Mcrypt you can use:
echo ( ! function_exists(’mcrypt_encrypt’)) ? ’Nope’ : ’Yup’;
$this->encrypt->set_mode();
Permits you to set an Mcrypt mode. By default it uses MCRYPT_MODE_CBC. Example:
$this->encrypt->set_mode(MCRYPT_MODE_CFB);
Please visit php.net for a list of available modes.
$this->encrypt->encode_from_legacy($orig_data, $legacy_mode = MCRYPT_MODE_ECB, $key = ‘’);
Enables you to re-encode data that was originally encrypted with CodeIgniter 1.x to be compatible with the Encryption
library in CodeIgniter 2.x. It is only necessary to use this method if you have encrypted data stored permanently such
as in a file or database and are on a server that supports Mcrypt. “Light” use encryption such as encrypted session data
or transitory encrypted flashdata require no intervention on your part. However, existing encrypted Sessions will be
destroyed since data encrypted prior to 2.x will not be decoded.
: Why only a method to re-encode the data instead of maintaining legacy methods for both encoding and
decoding? The algorithms in the Encryption library have improved in CodeIgniter 2.x both for performance and
security, and we do not wish to encourage continued use of the older methods. You can of course extend the Encryption
450
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
library if you wish and replace the new methods with the old and retain seamless compatibility with CodeIgniter 1.x
encrypted data, but this a decision that a developer should make cautiously and deliberately, if at all.
$new_data = $this->encrypt->encode_from_legacy($old_encrypted_string);
PaDefault
Description
rameter
$orig_datan/a
The original encrypted data from CodeIgniter 1.x’s Encryption library
$legacy_mode
MCRYPT_MODE_ECB
The Mcrypt mode that was used to generate the original encrypted data. CodeIgniter
1.x’s default was MCRYPT_MODE_ECB, and it will assume that to be the case unless
overridden by this parameter.
$key
n/a
The encryption key. This it typically specified in your config file as outlined above.
10.13.8 File Uploading Class
CodeIgniter’s File Uploading Class permits files to be uploaded. You can set various preferences, restricting the type
and size of the files.
The Process
Uploading a file involves the following general process:
• An upload form is displayed, allowing a user to select a file and upload it.
• When the form is submitted, the file is uploaded to the destination you specify.
• Along the way, the file is validated to make sure it is allowed to be uploaded based on the preferences you set.
• Once uploaded, the user will be shown a success message.
To demonstrate this process here is brief tutorial. Afterward you’ll find reference information.
Creating the Upload Form
Using a text editor, create a form called upload_form.php. In it, place this code and save it to your application/views/
directory:
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart(’upload/do_upload’);?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
10.13. Libraries
451
CodeIgniter Documentation, 3.0-dev
</body>
</html>
You’ll notice we are using a form helper to create the opening form tag. File uploads require a multipart form, so the
helper creates the proper syntax for you. You’ll also notice we have an $error variable. This is so we can show error
messages in the event the user does something wrong.
The Success Page
Using a text editor, create a form called upload_success.php. In it, place this code and save it to your application/views/ directory:
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor(’upload’, ’Upload Another File!’); ?></p>
</body>
</html>
The Controller
Using a text editor, create a controller called Upload.php. In it, place this code and save it to your application/controllers/ directory:
<?php
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array(’form’, ’url’));
}
public function index()
{
$this->load->view(’upload_form’, array(’error’ => ’ ’ ));
}
public function do_upload()
{
$config[’upload_path’]
$config[’allowed_types’]
452
= ’./uploads/’;
= ’gif|jpg|png’;
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$config[’max_size’]
$config[’max_width’]
$config[’max_height’]
= 100;
= 1024;
= 768;
$this->load->library(’upload’, $config);
if ( ! $this->upload->do_upload())
{
$error = array(’error’ => $this->upload->display_errors());
$this->load->view(’upload_form’, $error);
}
else
{
$data = array(’upload_data’ => $this->upload->data());
$this->load->view(’upload_success’, $data);
}
}
}
?>
The Upload Directory
You’ll need a destination directory for your uploaded images. Create a directory at the root of your CodeIgniter
installation called uploads and set its file permissions to 777.
Try it!
To try your form, visit your site using a URL similar to this one:
example.com/index.php/upload/
You should see an upload form. Try uploading an image file (either a jpg, gif, or png). If the path in your controller is
correct it should work.
Reference Guide
Initializing the Upload Class
Like most other classes in CodeIgniter, the Upload class is initialized in your controller using the
$this->load->library() method:
$this->load->library(’upload’);
Once the Upload class is loaded, the object will be available using: $this->upload
Setting Preferences
Similar to other libraries, you’ll control what is allowed to be upload based on your preferences. In the controller you
built above you set the following preferences:
10.13. Libraries
453
CodeIgniter Documentation, 3.0-dev
$config[’upload_path’] = ’./uploads/’;
$config[’allowed_types’] = ’gif|jpg|png’;
$config[’max_size’]
= ’100’;
$config[’max_width’] = ’1024’;
$config[’max_height’] = ’768’;
$this->load->library(’upload’, $config);
// Alternately you can set preferences by calling the ‘‘initialize()‘‘ method. Useful if you auto-loa
$this->upload->initialize($config);
The above preferences should be fairly self-explanatory. Below is a table describing all available preferences.
Preferences
The following preferences are available. The default value indicates what will be used if you do not specify that
preference.
454
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Preference
Default
Value
None
upload_path
alNone
lowed_types
Options
Description
None
The path to the directory where the upload should be placed. The directory
must be writable and the path can be absolute or relative.
None
The mime types corresponding to the types of files you allow to be
uploaded. Usually the file extension can be used as the mime type.
Separate multiple types with a pipe.
file_name
None
Desired
If set CodeIgniter will rename the uploaded file to this name. The
file name
extension provided in the file name must also be an allowed file type. If no
extension is provided in the original file_name will be used.
file_ext_tolower
FALSE TRUE/FALSEIf set to TRUE, the file extension will be forced to lower case
(boolean)
overwrite
FALSE TRUE/FALSEIf set to true, if a file with the same name as the one you are uploading
(boolean)
exists, it will be overwritten. If set to false, a number will be appended to
the filename if another with the same name exists.
max_size
0
None
The maximum size (in kilobytes) that the file can be. Set to zero for no
limit. Note: Most PHP installations have their own limit, as specified in the
php.ini file. Usually 2 MB (or 2048 KB) by default.
max_width 0
None
The maximum width (in pixels) that the image can be. Set to zero for no
limit.
max_height 0
None
The maximum height (in pixels) that the image can be. Set to zero for no
limit.
min_width 0
None
The minimum width (in pixels) that the image can be. Set to zero for no
limit.
min_height 0
None
The minimum height (in pixels) that the image can be. Set to zero for no
limit.
max_filename0
None
The maximum length that a file name can be. Set to zero for no limit.
max_filename_increment
100
None
When overwrite is set to FALSE, use this to set the maximum filename
increment for CodeIgniter to append to the filename.
enFALSE TRUE/FALSEIf set to TRUE the file name will be converted to a random encrypted
crypt_name
(boolean)
string. This can be useful if you would like the file saved with a name that
can not be discerned by the person uploading it.
reTRUE TRUE/FALSEIf set to TRUE, any spaces in the file name will be converted to
move_spaces
(boolean)
underscores. This is recommended.
deTRUE TRUE/FALSEIf set to TRUE, a server side detection of the file type will be performed to
tect_mime
(boolean)
avoid code injection attacks. DO NOT disable this option unless you have
no other option as that would cause a security risk.
mod_mime_fixTRUE TRUE/FALSEIf set to TRUE, multiple filename extensions will be suffixed with an
(boolean)
underscore in order to avoid triggering Apache mod_mime. DO NOT turn
off this option if your upload directory is public, as this is a security risk.
Setting preferences in a config file
If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create
a new file called the upload.php, add the $config array in that file. Then save the file in: config/upload.php and it
will be used automatically. You will NOT need to use the $this->upload->initialize() method if you save
your preferences in a config file.
Class Reference
The following methods are available:
10.13. Libraries
455
CodeIgniter Documentation, 3.0-dev
$this->upload->do_upload()
Performs the upload based on the preferences you’ve set.
: By default the upload routine expects the file to come from a form field called userfile, and the form must be of type
“multipart”.
<form method="post" action="some_action" enctype="multipart/form-data" />
If you would like to set your own field name simply pass its value to the do_upload() method:
$field_name = "some_field_name";
$this->upload->do_upload($field_name);
$this->upload->display_errors()
Retrieves any error messages if the do_upload() method returned false. The method does not echo automatically,
it returns the data so you can assign it however you need.
Formatting Errors By default the above method wraps any errors within <p> tags. You can set your own delimiters
like this:
$this->upload->display_errors(’<p>’, ’</p>’);
$this->upload->data()
This is a helper method that returns an array containing all of the data related to the file you uploaded. Here is the
array prototype:
Array
(
[file_name]
=> mypic.jpg
[file_type]
=> image/jpeg
[file_path]
=> /path/to/your/upload/
[full_path]
=> /path/to/your/upload/jpg.jpg
[raw_name]
=> mypic
[orig_name]
=> mypic.jpg
[client_name]
=> mypic.jpg
[file_ext]
=> .jpg
[file_size]
=> 22.2
[is_image]
=> 1
[image_width]
=> 800
[image_height] => 600
[image_type]
=> jpeg
[image_size_str] => width="800" height="200"
)
To return one element from the array:
$this->upload->data(’file_name’);
456
// Returns: mypic.jpg
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Explanation Here is an explanation of the above array items.
Item Description file_name The name of the file that was uploaded including the file extension. file_type The file’s
Mime type file_path The absolute server path to the file full_path The absolute server path including the file name
raw_name The file name without the extension orig_name The original file name. This is only useful if you use
the encrypted name option. client_name The file name as supplied by the client user agent, prior to any file name
preparation or incrementing. file_ext The file extension with period file_size The file size in kilobytes is_image
Whether the file is an image or not. 1 = image. 0 = not. image_width Image width. image_height Image height
image_type Image type. Typically the file extension without the period. image_size_str A string containing the width
and height. Useful to put into an image tag.
10.13.9 Form Validation
CodeIgniter provides a comprehensive form validation and data prepping class that helps minimize the amount of code
you’ll write.
10.13. Libraries
457
CodeIgniter Documentation, 3.0-dev
Page Contents
• Form Validation
– Overview
– Form Validation Tutorial
* The Form
* The Success Page
* The Controller
* Try it!
* Explanation
* Setting Validation Rules
* Setting Rules Using an Array
* Cascading Rules
* Prepping Data
* Re-populating the form
* Callbacks: Your own Validation Methods
* Setting Error Messages
* Translating Field Names
* Changing the Error Delimiters
* Showing Errors Individually
* Validating an Array (other than $_POST)
– Saving Sets of Validation Rules to a Config File
* How to save your rules
* Creating Sets of Rules
* Calling a Specific Rule Group
* Associating a Controller Method with a Rule Group
– Using Arrays as Field Names
– Rule Reference
– Prepping Reference
– Class Reference
* $this->form_validation->set_rules()
* $this->form_validation->run()
* $this->form_validation->set_message()
* $this->form_validation->set_data()
* $this->form_validation->reset_validation()
* $this->form_validation->error_array()
– Helper Reference
* form_error()
* validation_errors()
* set_value()
* set_select()
* set_checkbox()
* set_radio()
Overview
Before explaining CodeIgniter’s approach to data validation, let’s describe the ideal scenario:
1. A form is displayed.
2. You fill it in and submit it.
3. If you submitted something invalid, or perhaps missed a required item, the form is redisplayed containing your
data along with an error message describing the problem.
458
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
4. This process continues until you have submitted a valid form.
On the receiving end, the script must:
1. Check for required data.
2. Verify that the data is of the correct type, and meets the correct criteria. For example, if a username is submitted
it must be validated to contain only permitted characters. It must be of a minimum length, and not exceed a
maximum length. The username can’t be someone else’s existing username, or perhaps even a reserved word.
Etc.
3. Sanitize the data for security.
4. Pre-format the data if needed (Does the data need to be trimmed? HTML encoded? Etc.)
5. Prep the data for insertion in the database.
Although there is nothing terribly complex about the above process, it usually requires a significant amount of code,
and to display error messages, various control structures are usually placed within the form HTML. Form validation,
while simple to create, is generally very messy and tedious to implement.
Form Validation Tutorial
What follows is a “hands on” tutorial for implementing CodeIgniters Form Validation.
In order to implement form validation you’ll need three things:
1. A View file containing a form.
2. A View file containing a “success” message to be displayed upon successful submission.
3. A controller method to receive and process the submitted data.
Let’s create those three things, using a member sign-up form as the example.
The Form
Using a text editor, create a form called myform.php. In it, place this code and save it to your application/views/ folder:
<html>
<head>
<title>My Form</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open(’form’); ?>
<h5>Username</h5>
<input type="text" name="username" value="" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="" size="50" />
10.13. Libraries
459
CodeIgniter Documentation, 3.0-dev
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
The Success Page
Using a text editor, create a form called formsuccess.php. In it, place this code and save it to your application/views/
folder:
<html>
<head>
<title>My Form</title>
</head>
<body>
<h3>Your form was successfully submitted!</h3>
<p><?php echo anchor(’form’, ’Try it again!’); ?></p>
</body>
</html>
The Controller
Using a text editor, create a controller called form.php. In it, place this code and save it to your application/controllers/
folder:
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array(’form’, ’url’));
$this->load->library(’form_validation’);
if ($this->form_validation->run() == FALSE)
{
$this->load->view(’myform’);
}
else
{
$this->load->view(’formsuccess’);
}
}
}
Try it!
To try your form, visit your site using a URL similar to this one:
460
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
example.com/index.php/form/
If you submit the form you should simply see the form reload. That’s because you haven’t set up any validation rules
yet.
Since you haven’t told the Form Validation class to validate anything yet, it returns FALSE (boolean false) by
default. ‘‘The run()‘‘ method only returns TRUE if it has successfully applied your rules without any of them
failing.
Explanation
You’ll notice several things about the above pages:
The form (myform.php) is a standard web form with a couple exceptions:
1. It uses a form helper to create the form opening. Technically, this isn’t necessary. You could create the form
using standard HTML. However, the benefit of using the helper is that it generates the action URL for you, based
on the URL in your config file. This makes your application more portable in the event your URLs change.
2. At the top of the form you’ll notice the following function call:
<?php echo validation_errors(); ?>
This function will return any error messages sent back by the validator. If there are no messages it returns an
empty string.
The controller (form.php) has one method: index(). This method initializes the validation class and loads the form
helper and URL helper used by your view files. It also runs the validation routine. Based on whether the validation
was successful it either presents the form or the success page.
Setting Validation Rules
CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even
lets you prep and pre-process the field data at the same time. To set validation rules you will use the set_rules()
method:
$this->form_validation->set_rules();
The above method takes three parameters as input:
1. The field name - the exact name you’ve given the form field.
2. A “human” name for this field, which will be inserted into the error message. For example, if your field is named
“user” you might give it a human name of “Username”.
3. The validation rules for this form field.
: If you would like the field name to be stored in a language file, please see Translating Field Names.
Here is an example. In your controller (form.php), add this code just below the validation initialization method:
$this->form_validation->set_rules(’username’, ’Username’, ’required’);
$this->form_validation->set_rules(’password’, ’Password’, ’required’);
$this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’required’);
$this->form_validation->set_rules(’email’, ’Email’, ’required’);
Your controller should now look like this:
10.13. Libraries
461
CodeIgniter Documentation, 3.0-dev
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array(’form’, ’url’));
$this->load->library(’form_validation’);
$this->form_validation->set_rules(’username’, ’Username’, ’required’);
$this->form_validation->set_rules(’password’, ’Password’, ’required’);
$this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’required’);
$this->form_validation->set_rules(’email’, ’Email’, ’required’);
if ($this->form_validation->run() == FALSE)
{
$this->load->view(’myform’);
}
else
{
$this->load->view(’formsuccess’);
}
}
}
Now submit the form with the fields blank and you should see the error messages. If you submit the form with all the
fields populated you’ll see your success page.
: The form fields are not yet being re-populated with the data when there is an error. We’ll get to that shortly.
Setting Rules Using an Array
Before moving on it should be noted that the rule setting method can be passed an array if you prefer to set all your
rules in one action. If you use this approach, you must name your array keys as indicated:
$config = array(
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
462
=> ’username’,
=> ’Username’,
=> ’required’
=> ’password’,
=> ’Password’,
=> ’required’
=> ’passconf’,
=> ’Password Confirmation’,
=> ’required’
=> ’email’,
=> ’Email’,
=> ’required’
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
)
);
$this->form_validation->set_rules($config);
Cascading Rules
CodeIgniter lets you pipe multiple rules together. Let’s try it. Change your rules in the third parameter of rule setting
method, like this:
$this->form_validation->set_rules(’username’, ’Username’, ’required|min_length[5]|max_length[12]|is_u
$this->form_validation->set_rules(’password’, ’Password’, ’required’);
$this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’required|matches[password]’);
$this->form_validation->set_rules(’email’, ’Email’, ’required|valid_email|is_unique[users.email]’);
The above code sets the following rules:
1. The username field be no shorter than 5 characters and no longer than 12.
2. The password field must match the password confirmation field.
3. The email field must contain a valid email address.
Give it a try! Submit your form without the proper data and you’ll see new error messages that correspond to your
new rules. There are numerous rules available which you can read about in the validation reference.
: You can also pass an array of rules to set_rules(), instead of a string. Example:
$this->form_validation->set_rules(’username’, ’Username’, array(’required’, ’min_length[5]’));
Prepping Data
In addition to the validation method like the ones we used above, you can also prep your data in various ways. For
example, you can set up rules like this:
$this->form_validation->set_rules(’username’, ’Username’, ’trim|required|min_length[5]|max_length[12]
$this->form_validation->set_rules(’password’, ’Password’, ’trim|required|md5’);
$this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’trim|required|matches[passwor
$this->form_validation->set_rules(’email’, ’Email’, ’trim|required|valid_email’);
In the above example, we are “trimming” the fields, converting the password to MD5, and running the username
through the xss_clean() method, which removes malicious data.
Any native PHP function that accepts one parameter can be used as a rule, like htmlspecialchars, trim, md5,
etc.
: You will generally want to use the prepping functions after the validation rules so if there is an error, the original
data will be shown in the form.
Re-populating the form
Thus far we have only been dealing with errors. It’s time to repopulate the form field with the submitted data.
CodeIgniter offers several helper functions that permit you to do this. The one you will use most commonly is:
10.13. Libraries
463
CodeIgniter Documentation, 3.0-dev
set_value(’field name’)
Open your myform.php view file and update the value in each field using the set_value() function:
Don’t forget to include each field name in the ‘‘set_value()‘‘ functions!
<html>
<head>
<title>My Form</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open(’form’); ?>
<h5>Username</h5>
<input type="text" name="username" value="<?php echo set_value(’username’); ?>" size="50" />
<h5>Password</h5>
<input type="text" name="password" value="<?php echo set_value(’password’); ?>" size="50" />
<h5>Password Confirm</h5>
<input type="text" name="passconf" value="<?php echo set_value(’passconf’); ?>" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value(’email’); ?>" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
Now reload your page and submit the form so that it triggers an error. Your form fields should now be re-populated
: The Class Reference section below contains functions that permit you to re-populate <select> menus, radio buttons,
and checkboxes.
Important Note: If you use an array as the name of a form field, you must supply it as an array to the function.
Example:
<input type="text" name="colors[]" value="<?php echo set_value(’colors[]’); ?>" size="50" />
For more info please see the Using Arrays as Field Names section below.
Callbacks: Your own Validation Methods
The validation system supports callbacks to your own validation methods. This permits you to extend the validation
class to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique
username, you can create a callback method that does that. Let’s create an example of this.
In your controller, change the “username” rule to this:
$this->form_validation->set_rules(’username’, ’Username’, ’callback_username_check’);
464
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Then add a new method called username_check() to your controller. Here’s how your controller should now
look:
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array(’form’, ’url’));
$this->load->library(’form_validation’);
$this->form_validation->set_rules(’username’, ’Username’, ’callback_username_check’);
$this->form_validation->set_rules(’password’, ’Password’, ’required’);
$this->form_validation->set_rules(’passconf’, ’Password Confirmation’, ’required’);
$this->form_validation->set_rules(’email’, ’Email’, ’required|is_unique[users.email]’
if ($this->form_validation->run() == FALSE)
{
$this->load->view(’myform’);
}
else
{
$this->load->view(’formsuccess’);
}
}
public function username_check($str)
{
if ($str == ’test’)
{
$this->form_validation->set_message(’username_check’, ’The {field} field can
return FALSE;
}
else
{
return TRUE;
}
}
}
Reload your form and submit it with the word “test” as the username. You can see that the form field data was passed
to your callback method for you to process.
To invoke a callback just put the method name in a rule, with “callback_” as the rule prefix. If you need to receive an
extra parameter in your callback method, just add it normally after the method name between square brackets, as in:
“callback_foo**[bar]**”, then it will be passed as the second argument of your callback method.
: You can also process the form data that is passed to your callback and return it. If your callback returns anything
other than a boolean TRUE/FALSE it is assumed that the data is your newly processed form data.
Setting Error Messages
All of the native error messages are
tem/language/english/form_validation_lang.php
10.13. Libraries
located
in
the
following
language
file:
sys-
465
CodeIgniter Documentation, 3.0-dev
To set your own custom message you can either edit that file, or use the following method:
$this->form_validation->set_message(’rule’, ’Error Message’);
Where rule corresponds to the name of a particular rule, and Error Message is the text you would like displayed.
If you’d like to include a field’s “human” name, or the optional parameter some rules allow for (such as max_length),
you can add the {field} and {param} tags to your message, respectively:
$this->form_validation->set_message(’min_length’, ’{field} must have at least {param} characters.’);
On a field with the human name Username and a rule of min_length[5], an error would display: “Username must have
at least 5 characters.”
: The old sprintf() method of using %s in your error messages will still work, however it will override the tags above.
You should use one or the other.
In the callback rule example above, the error message was set by passing the name of the method (without the “callback_” prefix):
$this->form_validation->set_message(’username_check’)
Translating Field Names
If you would like to store the “human” name you passed to the set_rules() method in a language file, and therefore
make the name able to be translated, here’s how:
First, prefix your “human” name with lang:, as in this example:
$this->form_validation->set_rules(’first_name’, ’lang:first_name’, ’required’);
Then, store the name in one of your language file arrays (without the prefix):
$lang[’first_name’] = ’First Name’;
: If you store your array item in a language file that is not loaded automatically by CI, you’ll need to remember to
load it in your controller using:
$this->lang->load(’file_name’);
See the Language Class page for more info regarding language files.
Changing the Error Delimiters
By default, the Form Validation class adds a paragraph tag (<p>) around each error message shown. You can either
change these delimiters globally, individually, or change the defaults in a config file.
1. Changing delimiters Globally To globally change the error delimiters, in your controller method, just after
loading the Form Validation class, add this:
$this->form_validation->set_error_delimiters(’<div class="error">’, ’</div>’);
In this example, we’ve switched to using div tags.
2. Changing delimiters Individually Each of the two error generating functions shown in this tutorial can be
supplied their own delimiters as follows:
466
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
<?php echo form_error(’field name’, ’<div class="error">’, ’</div>’); ?>
Or:
<?php echo validation_errors(’<div class="error">’, ’</div>’); ?>
3. Set delimiters in a config file You can add your error delimiters in application/config/form_validation.php as
follows:
$config[’error_prefix’] = ’<div class="error_prefix">’;
$config[’error_suffix’] = ’</div>’;
Showing Errors Individually
If you prefer to show an error message next to each form field, rather than as a list, you can use the form_error()
function.
Try it! Change your form so that it looks like this:
<h5>Username</h5>
<?php echo form_error(’username’); ?>
<input type="text" name="username" value="<?php echo set_value(’username’); ?>" size="50" />
<h5>Password</h5>
<?php echo form_error(’password’); ?>
<input type="text" name="password" value="<?php echo set_value(’password’); ?>" size="50" />
<h5>Password Confirm</h5>
<?php echo form_error(’passconf’); ?>
<input type="text" name="passconf" value="<?php echo set_value(’passconf’); ?>" size="50" />
<h5>Email Address</h5>
<?php echo form_error(’email’); ?>
<input type="text" name="email" value="<?php echo set_value(’email’); ?>" size="50" />
If there are no errors, nothing will be shown. If there is an error, the message will appear.
: If you use an array as the name of a form field, you must supply it as an array to the function. Example:
<?php echo form_error(’options[size]’); ?>
<input type="text" name="options[size]" value="<?php echo set_value("options[size]"); ?>" size="50" /
For more info please see the Using Arrays as Field Names section below.
Validating an Array (other than $_POST)
Sometimes you may want to validate an array that does not originate from $_POST data.
In this case, you can specify the array to be validated:
$data = array(
’username’ => ’johndoe’,
’password’ => ’mypassword’,
’passconf’ => ’mypassword’
);
10.13. Libraries
467
CodeIgniter Documentation, 3.0-dev
$this->form_validation->set_data($data);
Creating validation rules, running the validation, and retrieving error messages works the same whether you are validating $_POST data or an array.
:
If you want to validate more than one array during a single execution, then you should call the
reset_validation() method before setting up rules and validating the new array.
For more info please see the Class Reference section below.
Saving Sets of Validation Rules to a Config File
A nice feature of the Form Validation class is that it permits you to store all your validation rules for your entire application in a config file. You can organize these rules into “groups”. These groups can either be loaded automatically
when a matching controller/method is called, or you can manually call each set as needed.
How to save your rules
To store your validation rules, simply create a file named form_validation.php in your application/config/ folder. In
that file you will place an array named $config with your rules. As shown earlier, the validation array will have this
prototype:
$config = array(
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
)
);
=> ’username’,
=> ’Username’,
=> ’required’
=> ’password’,
=> ’Password’,
=> ’required’
=> ’passconf’,
=> ’Password Confirmation’,
=> ’required’
=> ’email’,
=> ’Email’,
=> ’required’
Your validation rule file will be loaded automatically and used when you call the run() method.
Please note that you MUST name your $config array.
Creating Sets of Rules
In order to organize your rules into “sets” requires that you place them into “sub arrays”. Consider the following
example, showing two sets of rules. We’ve arbitrarily called these two rules “signup” and “email”. You can name your
rules anything you want:
468
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$config = array(
’signup’ => array(
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
)
),
’email’ => array(
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
),
array(
’field’
’label’
’rules’
)
)
);
=> ’username’,
=> ’Username’,
=> ’required’
=> ’password’,
=> ’Password’,
=> ’required’
=> ’passconf’,
=> ’Password Confirmation’,
=> ’required’
=> ’email’,
=> ’Email’,
=> ’required’
=> ’emailaddress’,
=> ’EmailAddress’,
=> ’required|valid_email’
=> ’name’,
=> ’Name’,
=> ’required|alpha’
=> ’title’,
=> ’Title’,
=> ’required’
=> ’message’,
=> ’MessageBody’,
=> ’required’
Calling a Specific Rule Group
In order to call a specific group, you will pass its name to the run() method. For example, to call the signup rule you
will do this:
if ($this->form_validation->run(’signup’) == FALSE)
{
$this->load->view(’myform’);
}
else
10.13. Libraries
469
CodeIgniter Documentation, 3.0-dev
{
$this->load->view(’formsuccess’);
}
Associating a Controller Method with a Rule Group
An alternate (and more automatic) method of calling a rule group is to name it according to the controller class/method
you intend to use it with. For example, let’s say you have a controller named Member and a method named signup.
Here’s what your class might look like:
<?php
class Member extends CI_Controller {
public function signup()
{
$this->load->library(’form_validation’);
if ($this->form_validation->run() == FALSE)
{
$this->load->view(’myform’);
}
else
{
$this->load->view(’formsuccess’);
}
}
}
In your validation config file, you will name your rule group member/signup:
$config = array(
’member/signup’ => array(
array(
’field’ =>
’label’ =>
’rules’ =>
),
array(
’field’ =>
’label’ =>
’rules’ =>
),
array(
’field’ =>
’label’ =>
’rules’ =>
),
array(
’field’ =>
’label’ =>
’rules’ =>
)
)
);
’username’,
’Username’,
’required’
’password’,
’Password’,
’required’
’passconf’,
’PasswordConfirmation’,
’required’
’email’,
’Email’,
’required’
When a rule group is named identically to a controller class/method it will be used automatically when the run()
470
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
method is invoked from that class/method.
Using Arrays as Field Names
The Form Validation class supports the use of arrays as field names. Consider this example:
<input type="text" name="options[]" value="" size="50" />
If you do use an array as a field name, you must use the EXACT array name in the Helper Functions that require the
field name, and as your Validation Rule field name.
For example, to set a rule for the above field you would use:
$this->form_validation->set_rules(’options[]’, ’Options’, ’required’);
Or, to show an error for the above field you would use:
<?php echo form_error(’options[]’); ?>
Or to re-populate the field you would use:
<input type="text" name="options[]" value="<?php echo set_value(’options[]’); ?>" size="50" />
You can use multidimensional arrays as field names as well. For example:
<input type="text" name="options[size]" value="" size="50" />
Or even:
<input type="text" name="sports[nba][basketball]" value="" size="50" />
As with our first example, you must use the exact array name in the helper functions:
<?php echo form_error(’sports[nba][basketball]’); ?>
If you are using checkboxes (or other fields) that have multiple options, don’t forget to leave an empty bracket after
each option, so that all selections will be added to the POST array:
<input type="checkbox" name="options[]" value="red" />
<input type="checkbox" name="options[]" value="blue" />
<input type="checkbox" name="options[]" value="green" />
Or if you use a multidimensional array:
<input type="checkbox" name="options[color][]" value="red" />
<input type="checkbox" name="options[color][]" value="blue" />
<input type="checkbox" name="options[color][]" value="green" />
When you use a helper function you’ll include the bracket as well:
<?php echo form_error(’options[color][]’); ?>
Rule Reference
The following is a list of all the native rules that are available to use:
10.13. Libraries
471
CodeIgniter Documentation, 3.0-dev
Rule
required
matches
differs
Parameter
No
Yes
Yes
is_unique
Yes
min_length Yes
max_length Yes
exYes
act_length
greater_than Yes
Description
Example
Returns FALSE if the form element is empty.
Returns FALSE if the form element does not match the one in the parameter.
Returns FALSE if the form element does not differ from the one in the
parameter.
Returns FALSE if the form element is not unique to the table and field name
in the parameter. Note: This rule requires Query Builder to be enabled in
order to work.
Returns FALSE if the form element is shorter then the parameter value.
Returns FALSE if the form element is longer then the parameter value.
Returns FALSE if the form element is not exactly the parameter value.
Returns FALSE if the form element is less than or equal to the parameter
value or not numeric.
greater_than_equal_to
Yes
Returns FALSE if the form element is less than the parameter value, or not
numeric.
less_than
Yes
Returns FALSE if the form element is greater than or equal to the parameter
value or not numeric.
less_than_equal_to
Yes
Returns FALSE if the form element is greater than the parameter value, or
not numeric.
alpha
No
Returns FALSE if the form element contains anything other than
alphabetical characters.
alNo
Returns FALSE if the form element contains anything other than
pha_numeric
alpha-numeric characters.
alNo
Returns FALSE if the form element contains anything other than
pha_numeric_spaces alpha-numeric characters or spaces. Should be used after trim to avoid
spaces at the beginning or end.
alNo
Returns FALSE if the form element contains anything other than
pha_dash
alpha-numeric characters, underscores or dashes.
numeric
No
Returns FALSE if the form element contains anything other than numeric
characters.
integer
No
Returns FALSE if the form element contains anything other than an integer.
decimal
No
Returns FALSE if the form element contains anything other than a decimal
number.
is_natural No
Returns FALSE if the form element contains anything other than a natural
number: 0, 1, 2, 3, etc.
is_natural_no_zero
No
Returns FALSE if the form element contains anything other than a natural
number, but not zero: 1, 2, 3, etc.
valid_url
No
Returns FALSE if the form element does not contain a valid URL.
valid_email No
Returns FALSE if the form element does not contain a valid email address.
valid_emails No
Returns FALSE if any value provided in a comma separated list is not a
valid email.
valid_ip
No
Returns FALSE if the supplied IP is not valid. Accepts an optional
parameter of ‘ipv4’ or ‘ipv6’ to specify an IP format.
valid_base64 No
Returns FALSE if the supplied string contains anything other than valid
Base64 characters.
matches[form_item]
differs[form_item]
is_unique[table.field]
min_length[3]
max_length[12]
exact_length[8]
greater_than[8]
greater_than_equal_to[8]
less_than[8]
less_than_equal_to[8]
: These rules can also be called as discrete methods. For example:
$this->form_validation->required($string);
: You can also use any native PHP functions that permit up to two parameters, where at least one is required (to pass
472
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
the field data).
Prepping Reference
The following is a list of all the prepping methods that are available to use:
Name
xss_clean
Parameter
No
prep_for_form
No
prep_url
No
strip_image_tags No
enNo
code_php_tags
Description
Runs the data through the XSS filtering method, described in the Security Class
page.
Converts special characters so that HTML data can be shown in a form field
without breaking it.
Adds “http://” to URLs if missing.
Strips the HTML from image tags leaving the raw URL.
Converts PHP tags to entities.
: You can also use any native PHP functions that permits one parameter, like trim(), htmlspecialchars(),
urldecode(), etc.
Class Reference
class Form_validation
The following methods are intended for use in your controller.
$this->form_validation->set_rules()
Form_validation::set_rules($field, $label = ‘’, $rules = ‘’)
• $field (string) – The field name
• $label (string) – The field label
• $rules (mixed) – The rules, as a string with rules separated by a pipe “|”, or an array
or rules.
Object
Permits you to set validation rules, as described in the tutorial sections above:
• Setting Validation Rules
• Saving Sets of Validation Rules to a Config File
$this->form_validation->run()
Form_validation::run($group = ‘’)
• $group (string) – The name of the validation group to run
Boolean
10.13. Libraries
473
CodeIgniter Documentation, 3.0-dev
Runs the validation routines. Returns boolean TRUE on success and FALSE on failure. You can
optionally pass the name of the validation group via the method, as described in: Saving Sets of
Validation Rules to a Config File
$this->form_validation->set_message()
Form_validation::set_message($lang, $val = ‘’)
• $lang (string) – The rule the message is for
• $val (string) – The message
Object
Permits you to set custom error messages. See Setting Error Messages
$this->form_validation->set_data()
Form_validation::set_data($data = ‘’)
• $data (array) – The data to validate
Permits you to set an array for validation, instead of using the default $_POST array.
$this->form_validation->reset_validation()
Form_validation::reset_validation()
Permits you to reset the validation when you validate more than one array. This method should be
called before validating each new array.
$this->form_validation->error_array()
Form_validation::error_array()
Array
Returns the error messages as an array.
Helper Reference
The following helper functions are available for use in the view files containing your forms. Note that these are
procedural functions, so they do not require you to prepend them with $this->form_validation.
form_error()
Shows an individual error message associated with the field name supplied to the function. Example:
<?php echo form_error(’username’); ?>
The error delimiters can be optionally specified. See the Changing the Error Delimiters section above.
474
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
validation_errors()
Shows all error messages as a string: Example:
<?php echo validation_errors(); ?>
The error delimiters can be optionally specified. See the Changing the Error Delimiters section above.
set_value()
Permits you to set the value of an input form or textarea. You must supply the field name via the first parameter of the
function. The second (optional) parameter allows you to set a default value for the form. Example:
<input type="text" name="quantity" value="<?php echo set_value(’quantity’, ’0’); ?>" size="50" />
The above form will show “0” when loaded for the first time.
set_select()
If you use a <select> menu, this function permits you to display the menu item that was selected. The first parameter
must contain the name of the select menu, the second parameter must contain the value of each item, and the third
(optional) parameter lets you set an item as the default (use boolean TRUE/FALSE).
Example:
<select name="myselect">
<option value="one" <?php echo set_select(’myselect’, ’one’, TRUE); ?> >One</option>
<option value="two" <?php echo set_select(’myselect’, ’two’); ?> >Two</option>
<option value="three" <?php echo set_select(’myselect’, ’three’); ?> >Three</option>
</select>
set_checkbox()
Permits you to display a checkbox in the state it was submitted. The first parameter must contain the name of the
checkbox, the second parameter must contain its value, and the third (optional) parameter lets you set an item as the
default (use boolean TRUE/FALSE). Example:
<input type="checkbox" name="mycheck[]" value="1" <?php echo set_checkbox(’mycheck[]’, ’1’); ?> />
<input type="checkbox" name="mycheck[]" value="2" <?php echo set_checkbox(’mycheck[]’, ’2’); ?> />
set_radio()
Permits you to display radio buttons in the state they were submitted. This function is identical to the set_checkbox()
function above.
<input type="radio" name="myradio" value="1" <?php echo set_radio(’myradio’, ’1’, TRUE); ?> />
<input type="radio" name="myradio" value="2" <?php echo set_radio(’myradio’, ’2’); ?> />
10.13. Libraries
475
CodeIgniter Documentation, 3.0-dev
10.13.10 FTP Class
CodeIgniter’s FTP Class permits files to be transfered to a remote server. Remote files can also be moved, renamed,
and deleted. The FTP class also includes a “mirroring” function that permits an entire local directory to be recreated
remotely via FTP.
: SFTP and SSL FTP protocols are not supported, only standard FTP.
Initializing the Class
Like most other classes in CodeIgniter, the FTP class is initialized in your controller using the $this->load->library
function:
$this->load->library(’ftp’);
Once loaded, the FTP object will be available using: $this->ftp
Usage Examples
In this example a connection is opened to the FTP server, and a local file is read and uploaded in ASCII mode. The
file permissions are set to 755.
$this->load->library(’ftp’);
$config[’hostname’] = ’ftp.example.com’;
$config[’username’] = ’your-username’;
$config[’password’] = ’your-password’;
$config[’debug’]
= TRUE;
$this->ftp->connect($config);
$this->ftp->upload(’/local/path/to/myfile.html’, ’/public_html/myfile.html’, ’ascii’, 0775);
$this->ftp->close();
In this example a list of files is retrieved from the server.
$this->load->library(’ftp’);
$config[’hostname’] = ’ftp.example.com’;
$config[’username’] = ’your-username’;
$config[’password’] = ’your-password’;
$config[’debug’]
= TRUE;
$this->ftp->connect($config);
$list = $this->ftp->list_files(’/public_html/’);
print_r($list);
$this->ftp->close();
In this example a local directory is mirrored on the server.
476
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$this->load->library(’ftp’);
$config[’hostname’] = ’ftp.example.com’;
$config[’username’] = ’your-username’;
$config[’password’] = ’your-password’;
$config[’debug’]
= TRUE;
$this->ftp->connect($config);
$this->ftp->mirror(’/path/to/myfolder/’, ’/public_html/myfolder/’);
$this->ftp->close();
Function Reference
$this->ftp->connect()
Connects and logs into to the FTP server. Connection preferences are set by passing an array to the function, or you
can store them in a config file.
Here is an example showing how you set preferences manually:
$this->load->library(’ftp’);
$config[’hostname’]
$config[’username’]
$config[’password’]
$config[’port’]
$config[’passive’]
$config[’debug’]
=
=
=
=
=
=
’ftp.example.com’;
’your-username’;
’your-password’;
21;
FALSE;
TRUE;
$this->ftp->connect($config);
Setting FTP Preferences in a Config File If you prefer you can store your FTP preferences in a config file. Simply
create a new file called the ftp.php, add the $config array in that file. Then save the file at config/ftp.php and it will be
used automatically.
Available connection options
• hostname - the FTP hostname. Usually something like: ftp.example.com
• username - the FTP username.
• password - the FTP password.
• port - The port number. Set to 21 by default.
• debug - TRUE/FALSE (boolean). Whether to enable debugging to display error messages.
• passive - TRUE/FALSE (boolean). Whether to use passive mode. Passive is set automatically by default.
$this->ftp->upload()
Uploads a file to your server. You must supply the local path and the remote path, and you can optionally set the mode
and permissions. Example:
10.13. Libraries
477
CodeIgniter Documentation, 3.0-dev
$this->ftp->upload(’/local/path/to/myfile.html’, ’/public_html/myfile.html’, ’ascii’, 0775);
Mode options are: ascii, binary, and auto (the default). If auto is used it will base the mode on the file extension of
the source file.
If set, permissions have to be passed as an octal value.
$this->ftp->download()
Downloads a file from your server. You must supply the remote path and the local path, and you can optionally set the
mode. Example:
$this->ftp->download(’/public_html/myfile.html’, ’/local/path/to/myfile.html’, ’ascii’);
Mode options are: ascii, binary, and auto (the default). If auto is used it will base the mode on the file extension of
the source file.
Returns FALSE if the download does not execute successfully (including if PHP does not have permission to write the
local file)
$this->ftp->rename()
Permits you to rename a file. Supply the source file name/path and the new file name/path.
// Renames green.html to blue.html
$this->ftp->rename(’/public_html/foo/green.html’, ’/public_html/foo/blue.html’);
$this->ftp->move()
Lets you move a file. Supply the source and destination paths:
// Moves blog.html from "joe" to "fred"
$this->ftp->move(’/public_html/joe/blog.html’, ’/public_html/fred/blog.html’);
Note: if the destination file name is different the file will be renamed.
$this->ftp->delete_file()
Lets you delete a file. Supply the source path with the file name.
$this->ftp->delete_file(’/public_html/joe/blog.html’);
$this->ftp->delete_dir()
Lets you delete a directory and everything it contains. Supply the source path to the directory with a trailing slash.
Important Be VERY careful with this function. It will recursively delete everything within the supplied path, including sub-folders and all files. Make absolutely sure your path is correct. Try using the list_files() function first to verify
that your path is correct.
$this->ftp->delete_dir(’/public_html/path/to/folder/’);
478
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$this->ftp->list_files()
Permits you to retrieve a list of files on your server returned as an array. You must supply the path to the desired
directory.
$list = $this->ftp->list_files(’/public_html/’);
print_r($list);
$this->ftp->mirror()
Recursively reads a local folder and everything it contains (including sub-folders) and creates a mirror via FTP based
on it. Whatever the directory structure of the original file path will be recreated on the server. You must supply a
source path and a destination path:
$this->ftp->mirror(’/path/to/myfolder/’, ’/public_html/myfolder/’);
$this->ftp->mkdir()
Lets you create a directory on your server. Supply the path ending in the folder name you wish to create, with a trailing
slash. Permissions can be set by passed an octal value in the second parameter (if you are running PHP 5).
// Creates a folder named "bar"
$this->ftp->mkdir(’/public_html/foo/bar/’, DIR_WRITE_MODE);
$this->ftp->chmod()
Permits you to set file permissions. Supply the path to the file or folder you wish to alter permissions on:
// Chmod "bar" to 777
$this->ftp->chmod(’/public_html/foo/bar/’, DIR_WRITE_MODE);
$this->ftp->close();
Closes the connection to your server. It’s recommended that you use this when you are finished uploading.
10.13.11 Image Manipulation Class
CodeIgniter’s Image Manipulation class lets you perform the following actions:
• Image Resizing
• Thumbnail Creation
• Image Cropping
• Image Rotating
• Image Watermarking
10.13. Libraries
479
CodeIgniter Documentation, 3.0-dev
All three major image libraries are supported: GD/GD2, NetPBM, and ImageMagick
: Watermarking is only available using the GD/GD2 library. In addition, even though other libraries are supported,
GD is required in order for the script to calculate the image properties. The image processing, however, will be
performed with the library you specify.
Initializing the Class
Like most other classes in CodeIgniter, the image class is initialized in your controller using the $this->load->library
function:
$this->load->library(’image_lib’);
Once the library is loaded it will be ready for use. The image library object you will use to call all functions is:
$this->image_lib
Processing an Image
Regardless of the type of processing you would like to perform (resizing, cropping, rotation, or watermarking), the
general process is identical. You will set some preferences corresponding to the action you intend to perform, then
call one of four available processing functions. For example, to create an image thumbnail you’ll do this:
$config[’image_library’] = ’gd2’;
$config[’source_image’] = ’/path/to/image/mypic.jpg’;
$config[’create_thumb’] = TRUE;
$config[’maintain_ratio’] = TRUE;
$config[’width’]
= 75;
$config[’height’]
= 50;
$this->load->library(’image_lib’, $config);
$this->image_lib->resize();
The above code tells the image_resize function to look for an image called mypic.jpg located in the source_image
folder, then create a thumbnail that is 75 X 50 pixels using the GD2 image_library. Since the maintain_ratio option
is enabled, the thumb will be as close to the target width and height as possible while preserving the original aspect
ratio. The thumbnail will be called mypic_thumb.jpg
: In order for the image class to be allowed to do any processing, the folder containing the image files must have write
permissions.
: Image processing can require a considerable amount of server memory for some operations. If you are experiencing
out of memory errors while processing images you may need to limit their maximum size, and/or adjust PHP memory
limits.
Processing Functions
There are four available processing functions:
• $this->image_lib->resize()
• $this->image_lib->crop()
480
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• $this->image_lib->rotate()
• $this->image_lib->watermark()
• $this->image_lib->clear()
These functions return boolean TRUE upon success and FALSE for failure. If they fail you can retrieve the error
message using this function:
echo $this->image_lib->display_errors();
A good practice is use the processing function conditionally, showing an error upon failure, like this:
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
: You can optionally specify the HTML formatting to be applied to the errors, by submitting the opening/closing tags
in the function, like this:
$this->image_lib->display_errors(’<p>’, ’</p>’);
Preferences
The preferences described below allow you to tailor the image processing to suit your needs.
Note that not all preferences are available for every function. For example, the x/y axis preferences are only available
for image cropping. Likewise, the width and height preferences have no effect on cropping. The “availability” column
indicates which functions support a given preference.
Availability Legend:
• R - Image Resizing
• C - Image Cropping
• X - Image Rotation
• W - Image Watermarking
10.13. Libraries
481
CodeIgniter Documentation, 3.0-dev
PrefDeerfault
ence
Value
imGD2
age_library
liNone
brary_path
source_image
None
Options
Description
Availability
GD, GD2,
ImageMagick,
NetPBM
None
Sets the image library to be used.
R, C,
X, W
Sets the server path to your ImageMagick or NetPBM library. If
you use either of those libraries you must supply the path.
R, C, X
R, C,
S, W
None
Sets the source image name/path. The path must be a relative or
absolute server path, not a URL.
dyFALSE TRUE/FALSE Determines whether the new image file should be written to disk or
namic_output
(boolean)
generated dynamically. Note: If you choose the dynamic setting,
only one image can be shown at a time, and it can’t be positioned
on the page. It simply outputs the raw image dynamically to your
browser, along with image headers.
qual90%
1 - 100%
Sets the quality of the image. The higher the quality the larger the
ity
file size.
new_image
None
None
Sets the destination image name/path. You’ll use this preference
when creating an image copy. The path must be a relative or
absolute server path, not a URL.
width
None
None
Sets the width you would like the image set to.
height None
None
Sets the height you would like the image set to.
creFALSE TRUE/FALSE Tells the image processing function to create a thumb.
ate_thumb
(boolean)
thumb_marker
_thumb None
Specifies the thumbnail indicator. It will be inserted just before the
file extension, so mypic.jpg would become mypic_thumb.jpg
mainTRUE TRUE/FALSE Specifies whether to maintain the original aspect ratio when
tain_ratio
(boolean)
resizing or use hard values.
masauto
auto, width,
Specifies what to use as the master axis when resizing or creating
ter_dim
height
thumbs. For example, let’s say you want to resize an image to 100
X 75 pixels. If the source image size does not allow perfect
resizing to those dimensions, this setting determines which axis
should be used as the hard value. “auto” sets the axis automatically
based on whether the image is taller then wider, or vice versa.
rotaNone
90, 180, 270,
Specifies the angle of rotation when rotating images. Note that
tion_angle
vrt, hor
PHP rotates counter-clockwise, so a 90 degree rotation to the right
must be specified as 270.
x_axis None
None
Sets the X coordinate in pixels for image cropping. For example, a
setting of 30 will crop an image 30 pixels from the left.
y_axis None
None
Sets the Y coordinate in pixels for image cropping. For example, a
setting of 30 will crop an image 30 pixels from the top.
R, C,
X, W
R, C,
X, W
R, C,
X, W
R, C
R, C
R
R
R, C
R
X
C
C
Setting preferences in a config file
If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create
a new file called image_lib.php, add the $config array in that file. Then save the file in: config/image_lib.php and
it will be used automatically. You will NOT need to use the $this->image_lib->initialize function if you save your
preferences in a config file.
482
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$this->image_lib->resize()
The image resizing function lets you resize the original image, create a copy (with or without resizing), or create a
thumbnail image.
For practical purposes there is no difference between creating a copy and creating a thumbnail except a thumb will
have the thumbnail marker as part of the name (ie, mypic_thumb.jpg).
All preferences listed in the table above are available for this function except these three: rotation_angle, x_axis, and
y_axis.
Creating a Thumbnail The resizing function will create a thumbnail file (and preserve the original) if you set this
preference to TRUE:
$config[’create_thumb’] = TRUE;
This single preference determines whether a thumbnail is created or not.
Creating a Copy The resizing function will create a copy of the image file (and preserve the original) if you set a
path and/or a new filename using this preference:
$config[’new_image’] = ’/path/to/new_image.jpg’;
Notes regarding this preference:
• If only the new image name is specified it will be placed in the same folder as the original
• If only the path is specified, the new image will be placed in the destination with the same name as the original.
• If both the path and image name are specified it will placed in its own destination and given the new name.
Resizing the Original Image If neither of the two preferences listed above (create_thumb, and new_image) are
used, the resizing function will instead target the original image for processing.
$this->image_lib->crop()
The cropping function works nearly identically to the resizing function except it requires that you set preferences for
the X and Y axis (in pixels) specifying where to crop, like this:
$config[’x_axis’] = ’100’;
$config[’y_axis’] = ’40’;
All preferences listed in the table above are available for this function except these: rotation_angle, create_thumb,
new_image.
Here’s an example showing how you might crop an image:
$config[’image_library’] = ’imagemagick’;
$config[’library_path’] = ’/usr/X11R6/bin/’;
$config[’source_image’] = ’/path/to/image/mypic.jpg’;
$config[’x_axis’] = ’100’;
$config[’y_axis’] = ’60’;
$this->image_lib->initialize($config);
if ( ! $this->image_lib->crop())
10.13. Libraries
483
CodeIgniter Documentation, 3.0-dev
{
echo $this->image_lib->display_errors();
}
: Without a visual interface it is difficult to crop images, so this function is not very useful unless you intend to build
such an interface. That’s exactly what we did using for the photo gallery module in ExpressionEngine, the CMS we
develop. We added a JavaScript UI that lets the cropping area be selected.
$this->image_lib->rotate()
The image rotation function requires that the angle of rotation be set via its preference:
$config[’rotation_angle’] = ’90’;
There are 5 rotation options:
1. 90 - rotates counter-clockwise by 90 degrees.
2. 180 - rotates counter-clockwise by 180 degrees.
3. 270 - rotates counter-clockwise by 270 degrees.
4. hor - flips the image horizontally.
5. vrt - flips the image vertically.
Here’s an example showing how you might rotate an image:
$config[’image_library’] = ’netpbm’;
$config[’library_path’] = ’/usr/bin/’;
$config[’source_image’] = ’/path/to/image/mypic.jpg’;
$config[’rotation_angle’] = ’hor’;
$this->image_lib->initialize($config);
if ( ! $this->image_lib->rotate())
{
echo $this->image_lib->display_errors();
}
$this->image_lib->clear()
The clear function resets all of the values used when processing an image. You will want to call this if you are
processing images in a loop.
$this->image_lib->clear();
Image Watermarking
The Watermarking feature requires the GD/GD2 library.
Two Types of Watermarking
There are two types of watermarking that you can use:
484
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• Text: The watermark message will be generating using text, either with a True Type font that you specify, or
using the native text output that the GD library supports. If you use the True Type version your GD installation
must be compiled with True Type support (most are, but not all).
• Overlay: The watermark message will be generated by overlaying an image (usually a transparent PNG or GIF)
containing your watermark over the source image.
Watermarking an Image
Just as with the other functions (resizing, cropping, and rotating) the general process for watermarking involves setting
the preferences corresponding to the action you intend to perform, then calling the watermark function. Here is an
example:
$config[’source_image’] = ’/path/to/image/mypic.jpg’;
$config[’wm_text’] = ’Copyright 2006 - John Doe’;
$config[’wm_type’] = ’text’;
$config[’wm_font_path’] = ’./system/fonts/texb.ttf’;
$config[’wm_font_size’] = ’16’;
$config[’wm_font_color’] = ’ffffff’;
$config[’wm_vrt_alignment’] = ’bottom’;
$config[’wm_hor_alignment’] = ’center’;
$config[’wm_padding’] = ’20’;
$this->image_lib->initialize($config);
$this->image_lib->watermark();
The above example will use a 16 pixel True Type font to create the text “Copyright 2006 - John Doe”. The watermark
will be positioned at the bottom/center of the image, 20 pixels from the bottom of the image.
: In order for the image class to be allowed to do any processing, the image file must have “write” file permissions
For example, 777.
Watermarking Preferences
This table shown the preferences that are available for both types of watermarking (text or overlay)
10.13. Libraries
485
CodeIgniter Documentation, 3.0-dev
Preference
wm_type
Default
Value
text
source_image
None
Options
Description
text,
overlay
None
Sets the type of watermarking that should be used.
Sets the source image name/path. The path must be a relative or absolute
server path, not a URL.
dyFALSE TRUE/FALSEDetermines whether the new image file should be written to disk or generated
namic_output
(boolean)
dynamically. Note: If you choose the dynamic setting, only one image can
be shown at a time, and it can’t be positioned on the page. It simply outputs
the raw image dynamically to your browser, along with image headers.
quality
90%
1 - 100%
Sets the quality of the image. The higher the quality the larger the file size.
wm_padding
None
A number
The amount of padding, set in pixels, that will be applied to the watermark to
set it away from the edge of your images.
wm_vrt_alignment
bottop,
Sets the vertical alignment for the watermark image.
tom
middle,
bottom
wm_hor_alignment
center
left, center, Sets the horizontal alignment for the watermark image.
right
wm_hor_offset
None
None
You may specify a horizontal offset (in pixels) to apply to the watermark
position. The offset normally moves the watermark to the right, except if you
have your alignment set to “right” then your offset value will move the
watermark toward the left of the image.
wm_vrt_offset
None
None
You may specify a vertical offset (in pixels) to apply to the watermark
position. The offset normally moves the watermark down, except if you have
your alignment set to “bottom” then your offset value will move the
watermark toward the top of the image.
Text Preferences This table shown the preferences that are available for the text type of watermarking.
Preference
wm_text
Default
Value
None
Op- Description
tions
None The text you would like shown as the watermark. Typically this will be a
copyright notice.
wm_font_pathNone
None The server path to the True Type Font you would like to use. If you do not use
this option, the native GD font will be used.
wm_font_size16
None The size of the text. Note: If you are not using the True Type option above, the
number is set using a range of 1 - 5. Otherwise, you can use any valid pixel size
for the font you’re using.
wm_font_color
ffffff
None The font color, specified in hex. Both the full 6-length (ie, 993300) and the short
three character abbreviated version (ie, fff) are supported.
wm_shadow_color
None
None The color of the drop shadow, specified in hex. If you leave this blank a drop
shadow will not be used. Both the full 6-length (ie, 993300) and the short three
character abbreviated version (ie, fff) are supported.
wm_shadow_distance
3
None The distance (in pixels) from the font that the drop shadow should appear.
Overlay Preferences This table shown the preferences that are available for the overlay type of watermarking.
486
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Preference
Default
Value
wm_overlay_path
None
Options
Description
None
wm_opacity50
1100
wm_x_transp
4
A
number
wm_y_transp
4
A
number
The server path to the image you wish to use as your watermark. Required only if
you are using the overlay method.
Image opacity. You may specify the opacity (i.e. transparency) of your watermark
image. This allows the watermark to be faint and not completely obscure the
details from the original image behind it. A 50% opacity is typical.
If your watermark image is a PNG or GIF image, you may specify a color on the
image to be “transparent”. This setting (along with the next) will allow you to
specify that color. This works by specifying the “X” and “Y” coordinate pixel
(measured from the upper left) within the image that corresponds to a pixel
representative of the color you want to be transparent.
Along with the previous setting, this allows you to specify the coordinate to a pixel
representative of the color you want to be transparent.
10.13.12 Input Class
The Input Class serves two purposes:
1. It pre-processes global input data for security.
2. It provides some helper methods for fetching input data and pre-processing it.
: This class is initialized automatically by the system so there is no need to do it manually.
Security Filtering
The security filtering method is called automatically when a new controller is invoked. It does the following:
• If $config[’allow_get_array’] is FALSE (default is TRUE), destroys the global GET array.
• Destroys all global variables in the event register_globals is turned on.
• Filters the GET/POST/COOKIE array keys, permitting only alpha-numeric (and a few other) characters.
• Provides XSS (Cross-site Scripting Hacks) filtering. This can be enabled globally, or upon request.
• Standardizes newline characters to \n(In Windows \r\n)
XSS Filtering
The Input class has the ability to filter input automatically to prevent cross-site scripting attacks. If you want the
filter to run automatically every time it encounters POST or COOKIE data you can enable it by opening your application/config/config.php file and setting this:
$config[’global_xss_filtering’] = TRUE;
Please refer to the Security class documentation for information on using XSS Filtering in your application.
Using POST, GET, COOKIE, or SERVER Data
CodeIgniter comes with four helper methods that let you fetch POST, GET, COOKIE or SERVER items. The main
advantage of using the provided methods rather than fetching an item directly ($_POST[’something’]) is that
10.13. Libraries
487
CodeIgniter Documentation, 3.0-dev
the methods will check to see if the item is set and return NULL if not. This lets you conveniently use data without
having to test whether an item exists first. In other words, normally you might do something like this:
$something = isset($_POST[’something’]) ? $_POST[’something’] : NULL;
With CodeIgniter’s built in methods you can simply do this:
$something = $this->input->post(’something’);
The four methods are:
• $this->input->post()
• $this->input->get()
• $this->input->cookie()
• $this->input->server()
$this->input->post()
The first parameter will contain the name of the POST item you are looking for:
$this->input->post(’some_data’);
The method returns NULL if the item you are attempting to retrieve does not exist.
The second optional parameter lets you run the data through the XSS filter. It’s enabled by setting the second parameter
to boolean TRUE;
$this->input->post(’some_data’, TRUE);
To return an array of all POST items call without any parameters.
To return all POST items and pass them through the XSS filter set the first parameter NULL while setting the second
parameter to boolean;
The method returns NULL if there are no items in the POST.
$this->input->post(NULL, TRUE); // returns all POST items with XSS filter
$this->input->post(); // returns all POST items without XSS filter
$this->input->get()
This method is identical to the POST method, only it fetches GET data
$this->input->get(’some_data’, TRUE);
To return an array of all GET items call without any parameters.
To return all GET items and pass them through the XSS filter set the first parameter NULL while setting the second
parameter to boolean;
The method returns NULL if there are no items in the GET.
$this->input->get(NULL, TRUE); // returns all GET items with XSS filter
$this->input->get(); // returns all GET items without XSS filtering
488
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$this->input->post_get()
This method will search through both the POST and GET streams for data, looking first in POST, and then in GET:
$this->input->post_get(’some_data’, TRUE);
$this->input->get_post()
This method will search through both the POST and GET streams for data, looking first in GET, and then in POST:
$this->input->get_post(’some_data’, TRUE);
$this->input->cookie()
This method is identical to the POST method, only it fetches cookie data
$this->input->cookie(’some_cookie’);
$this->input->cookie(’some_cookie, TRUE); // with XSS filter
$this->input->server()
This method is identical to the above methods, only it fetches server server data:
$this->input->server(’some_data’);
Using the php://input stream
If you want to utilize the PUT, DELETE, PATCH or other exotic request methods, they can only be accessed via a
special input stream, that can only be read once. This isn’t as easy as just reading from e.g. the $_POST array, because
it will always exist and you can try and access multiple variables without caring that you might only have one shot at
all of the POST data.
CodeIgniter will take care of that for you, and you can access data from the php://input stream at any time, just by
calling the input_stream() method:
$this->input->input_stream(’key’);
Similar to the methods above, if the requested data is not found, it will return NULL and you can also decide whether
to run the data through xss_clean() by passing a boolean value as the second parameter:
$this->input->input_stream(’key’, TRUE); // XSS Clean
$this->input->input_stream(’key’, FALSE); // No XSS filter
: You can utilize method() in order to know if you’re reading PUT, DELETE or PATCH data.
$this->input->set_cookie()
Sets a cookie containing the values you specify. There are two ways to pass information to this method so that a cookie
can be set: Array Method, and Discrete Parameters:
10.13. Libraries
489
CodeIgniter Documentation, 3.0-dev
Array Method
Using this method, an associative array is passed to the first parameter:
$cookie = array(
’name’
=> ’The Cookie Name’,
’value’ => ’The Value’,
’expire’ => ’86500’,
’domain’ => ’.some-domain.com’,
’path’
=> ’/’,
’prefix’ => ’myprefix_’,
’secure’ => TRUE
);
$this->input->set_cookie($cookie);
Notes:
Only the name and value are required. To delete a cookie set it with the expiration blank.
The expiration is set in seconds, which will be added to the current time. Do not include the time, but rather only the
number of seconds from now that you wish the cookie to be valid. If the expiration is set to zero the cookie will only
last as long as the browser is open.
For site-wide cookies regardless of how your site is requested, add your URL to the domain starting with a period,
like this: .your-domain.com
The path is usually not needed since the method sets a root path.
The prefix is only needed if you need to avoid name collisions with other identically named cookies for your server.
The secure boolean is only needed if you want to make it a secure cookie by setting it to TRUE.
Discrete Parameters
If you prefer, you can set the cookie by passing data using individual parameters:
$this->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure);
$this->input->ip_address()
Returns the IP address for the current user. If the IP address is not valid, the method will return an IP of: 0.0.0.0
echo $this->input->ip_address();
$this->input->valid_ip($ip)
Takes an IP address as input and returns TRUE or FALSE (boolean) if it is valid or not.
: The $this->input->ip_address() method above automatically validates the IP address.
if ( ! $this->input->valid_ip($ip))
{
echo ’Not Valid’;
}
else
490
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
{
echo ’Valid’;
}
Accepts an optional second string parameter of ‘ipv4’ or ‘ipv6’ to specify an IP format. The default checks for both
formats.
$this->input->user_agent()
Returns the user agent (web browser) being used by the current user. Returns FALSE if it’s not available.
echo $this->input->user_agent();
See the User Agent Class for methods which extract information from the user agent string.
$this->input->request_headers()
Useful if running in a non-Apache environment where apache_request_headers() will not be supported. Returns an
array of headers.
$headers = $this->input->request_headers();
$this->input->get_request_header()
Returns a single member of the request headers array.
$this->input->get_request_header(’some-header’, TRUE);
$this->input->is_ajax_request()
Checks to see if the HTTP_X_REQUESTED_WITH server header has been set, and returns a boolean response.
$this->input->is_cli_request()
Checks to see if the STDIN constant is set, which is a failsafe way to see if PHP is being run on the command line.
$this->input->is_cli_request()
: This method is DEPRECATED and is now just an alias for the is_cli() function.
$this->input->method()
Returns the $_SERVER[’REQUEST_METHOD’], optional set uppercase or lowercase (default lowercase).
echo $this->input->method(TRUE); // Outputs: POST
echo $this->input->method(FALSE); // Outputs: post
echo $this->input->method(); // Outputs: post
: This driver is experimental. Its feature set and implementation may change in future releases.
10.13. Libraries
491
CodeIgniter Documentation, 3.0-dev
10.13.13 Javascript Class
CodeIgniter provides a library to help you with certain common functions that you may want to use with Javascript.
Please note that CodeIgniter does not require the jQuery library to run, and that any scripting library will work equally
well. The jQuery library is simply presented as a convenience if you choose to use it.
Initializing the Class
To initialize the Javascript class manually in your controller constructor, use the $this->load->library function. Currently, the only available library is jQuery, which will automatically be loaded like this:
$this->load->library(’javascript’);
The Javascript class also accepts parameters, js_library_driver (string) default ‘jquery’ and autoload (bool) default
TRUE. You may override the defaults if you wish by sending an associative array:
$this->load->library(’javascript’, array(’js_library_driver’ => ’scripto’, ’autoload’ => FALSE));
Again, presently only ‘jquery’ is available. You may wish to set autoload to FALSE, though, if you do not want the
jQuery library to automatically include a script tag for the main jQuery script file. This is useful if you are loading it
from a location outside of CodeIgniter, or already have the script tag in your markup.
Once loaded, the jQuery library object will be available using: $this->javascript
Setup and Configuration
Set these variables in your view
As a Javascript library, your files must be available to your application.
As Javascript is a client side language, the library must be able to write content into your final output. This generally
means a view. You’ll need to include the following variables in the <head> sections of your output.
<?php echo $library_src;?>
<?php echo $script_head;?>
$library_src, is where the actual library file will be loaded, as well as any subsequent plugin script calls; $script_head
is where specific events, functions and other commands will be rendered.
Set the path to the librarys with config items
There are some configuration items in Javascript library. These can either be set in application/config.php, within its
own config/javascript.php file, or within any controller usings the set_item() function.
An image to be used as an “ajax loader”, or progress indicator. Without one, the simple text message of “loading” will
appear when Ajax calls need to be made.
$config[’javascript_location’] = ’http://localhost/codeigniter/themes/js/jquery/’;
$config[’javascript_ajax_img’] = ’images/ajax-loader.gif’;
If you keep your files in the same directories they were downloaded from, then you need not set this configuration
items.
492
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
The jQuery Class
To initialize the jQuery class manually in your controller constructor, use the $this->load->library function:
$this->load->library(’javascript/jquery’);
You may send an optional parameter to determine whether or not a script tag for the main jQuery file will be automatically included when loading the library. It will be created by default. To prevent this, load the library as follows:
$this->load->library(’javascript/jquery’, FALSE);
Once loaded, the jQuery library object will be available using: $this->jquery
jQuery Events
Events are set using the following syntax.
$this->jquery->event(’element_path’, code_to_run());
In the above example:
• “event” is any of blur, change, click, dblclick, error, focus, hover, keydown, keyup, load, mousedown, mouseup,
mouseover, mouseup, resize, scroll, or unload.
• “element_path” is any valid jQuery selector. Due to jQuery’s unique selector syntax, this is usually an element
id, or CSS selector. For example “#notice_area” would effect <div id=”notice_area”>, and “#content a.notice”
would effect all anchors with a class of “notice” in the div with id “content”.
• “code_to_run()” is script your write yourself, or an action such as an effect from the jQuery library below.
Effects
The query library supports a powerful Effects repertoire. Before an effect can be used, it must be loaded:
$this->jquery->effect([optional path] plugin name); // for example $this->jquery->effect(’bounce’);
hide() / show()
Each of this functions will affect the visibility of an item on your page. hide() will set an item invisible, show() will
reveal it.
$this->jquery->hide(target, optional speed, optional extra information);
$this->jquery->show(target, optional speed, optional extra information);
• “target” will be any valid jQuery selector or selectors.
• “speed” is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
• “extra information” is optional, and could include a callback, or other additional information.
toggle()
toggle() will change the visibility of an item to the opposite of its current state, hiding visible elements, and revealing
hidden ones.
10.13. Libraries
493
CodeIgniter Documentation, 3.0-dev
$this->jquery->toggle(target);
• “target” will be any valid jQuery selector or selectors.
animate()
$this->jquery->animate(target, parameters, optional speed, optional extra information);
• “target” will be any valid jQuery selector or selectors.
• “parameters” in jQuery would generally include a series of CSS properties that you wish to change.
• “speed” is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
• “extra information” is optional, and could include a callback, or other additional information.
For a full summary, see http://docs.jquery.com/Effects/animate
Here is an example of an animate() called on a div with an id of “note”, and triggered by a click using the jQuery
library’s click() event.
$params = array(
’height’ => 80,
’width’ => ’50%’,
’marginLeft’ => 125
);
$this->jquery->click(’#trigger’, $this->jquery->animate(’#note’, $params, ’normal’));
fadeIn() / fadeOut()
$this->jquery->fadeIn(target, optional speed, optional extra information);
$this->jquery->fadeOut(target, optional speed, optional extra information);
• “target” will be any valid jQuery selector or selectors.
• “speed” is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
• “extra information” is optional, and could include a callback, or other additional information.
toggleClass()
This function will add or remove a CSS class to its target.
$this->jquery->toggleClass(target, class)
• “target” will be any valid jQuery selector or selectors.
• “class” is any CSS classname. Note that this class must be defined and available in a CSS that is already loaded.
fadeIn() / fadeOut()
These effects cause an element(s) to disappear or reappear over time.
$this->jquery->fadeIn(target, optional speed, optional extra information);
$this->jquery->fadeOut(target, optional speed, optional extra information);
494
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
• “target” will be any valid jQuery selector or selectors.
• “speed” is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
• “extra information” is optional, and could include a callback, or other additional information.
slideUp() / slideDown() / slideToggle()
These effects cause an element(s) to slide.
$this->jquery->slideUp(target, optional speed, optional extra information);
$this->jquery->slideDown(target, optional speed, optional extra information);
$this->jquery->slideToggle(target, optional speed, optional extra information);
• “target” will be any valid jQuery selector or selectors.
• “speed” is optional, and is set to either slow, normal, fast, or alternatively a number of milliseconds.
• “extra information” is optional, and could include a callback, or other additional information.
Plugins
Some select jQuery plugins are made available using this library.
corner()
Used to add distinct corners to page elements. For full details see http://www.malsup.com/jquery/corner/
$this->jquery->corner(target, corner_style);
• “target” will be any valid jQuery selector or selectors.
• “corner_style” is optional, and can be set to any valid style such as round, sharp, bevel, bite, dog, etc. Individual
corners can be set by following the style with a space and using “tl” (top left), “tr” (top right), “bl” (bottom left),
or “br” (bottom right).
$this->jquery->corner("#note", "cool tl br");
tablesorter()
description to come
modal()
description to come
calendar()
description to come
10.13. Libraries
495
CodeIgniter Documentation, 3.0-dev
10.13.14 Language Class
The Language Class provides functions to retrieve language files and lines of text for purposes of internationalization.
In your CodeIgniter system folder you’ll find one called language containing sets of language files. You can create
your own language files as needed in order to display error and other messages in other languages.
Language files are typically stored in your system/language/ directory. Alternately you can create a directory called
language inside your application folder and store them there. CodeIgniter will always load the one in system/language/
first and will then look for an override in your application/language/ directory.
:
Each language should be stored in its own folder.
tem/language/english
For example, the English files are located at: sys-
Creating Language Files
Language files must be named with _lang.php as the file extension. For example, let’s say you want to create a file
containing error messages. You might name it: error_lang.php
Within the file you will assign each line of text to an array called $lang with this prototype:
$lang[’language_key’] = ’The actual message to be shown’;
: It’s a good practice to use a common prefix for all messages in a given file to avoid collisions with similarly named
items in other files. For example, if you are creating error messages you might prefix them with error_
$lang[’error_email_missing’] = ’You must submit an email address’;
$lang[’error_url_missing’] = ’You must submit a URL’;
$lang[’error_username_missing’] = ’You must submit a username’;
Loading A Language File
In order to fetch a line from a particular file you must load the file first. Loading a language file is done with the
following code:
$this->lang->load(’filename’, ’language’);
Where filename is the name of the file you wish to load (without the file extension), and language is the language set containing it (ie, english). If the second parameter is missing, the default language set in your application/config/config.php file will be used.
: The language parameter can only consist of letters.
Fetching a Line of Text
Once your desired language file is loaded you can access any line of text using this function:
$this->lang->line(’language_key’);
Where language_key is the array key corresponding to the line you wish to show.
You can optionally pass FALSE as the second argument of that method to disable error logging, in case you’re not
sure if the line exists:
496
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$this->lang->line(’misc_key’, FALSE);
: This method simply returns the line. It does not echo it.
Using language lines as form labels
This feature has been deprecated from the language library and moved to the lang() function of the Language
Helper.
Auto-loading Languages
If you find that you need a particular language globally throughout your application, you can tell CodeIgniter to autoload it during system initialization. This is done by opening the application/config/autoload.php file and adding the
language(s) to the autoload array.
10.13.15 Loader Class
Loader, as the name suggests, is used to load elements. These elements can be libraries (classes) View files, Drivers,
Helpers, Models, or your own files.
: This class is initialized automatically by the system so there is no need to do it manually.
The following methods are available in this class:
$this->load->library(‘class_name’, $config, ‘object name’)
This method is used to load core classes. Where class_name is the name of the class you want to load.
: We use the terms “class” and “library” interchangeably.
For example, if you would like to send email with CodeIgniter, the first step is to load the email class within your
controller:
$this->load->library(’email’);
Once loaded, the library will be ready for use, using $this->email->*some_method*().
Library files can be stored in subdirectories within the main “libraries” directory, or within your personal application/libraries directory. To load a file located in a subdirectory, simply include the path, relative to the “libraries”
directory. For example, if you have file located at:
libraries/flavors/Chocolate.php
You will load it using:
$this->load->library(’flavors/chocolate’);
You may nest the file in as many subdirectories as you want.
Additionally, multiple libraries can be loaded at the same time by passing an array of libraries to the load method.
10.13. Libraries
497
CodeIgniter Documentation, 3.0-dev
$this->load->library(array(’email’, ’table’));
Setting options
The second (optional) parameter allows you to optionally pass configuration setting. You will typically pass these as
an array:
$config = array (
’mailtype’ => ’html’,
’charset’ => ’utf-8,
’priority’ => ’1’
);
$this->load->library(’email’, $config);
Config options can usually also be set via a config file. Each library is explained in detail in its own page, so please
read the information regarding each one you would like to use.
Please take note, when multiple libraries are supplied in an array for the first parameter, each will receive the same
parameter information.
Assigning a Library to a different object name
If the third (optional) parameter is blank, the library will usually be assigned to an object with the same name as the
library. For example, if the library is named Calendar, it will be assigned to a variable named $this->calendar.
If you prefer to set your own class names you can pass its value to the third parameter:
$this->load->library(’calendar’, ’’, ’my_calendar’);
// Calendar class is now accessed using:
$this->my_calendar
Please take note, when multiple libraries are supplied in an array for the first parameter, this parameter is discarded.
$this->load->driver(‘parent_name’, $config, ‘object name’)
This method is used to load driver libraries. Where parent_name is the name of the parent class you want to load.
As an example, if you would like to use sessions with CodeIgniter, the first step is to load the session driver within
your controller:
$this->load->driver(’session’);
Once loaded, the library will be ready for use, using $this->session->*some_method*().
Driver files must be stored in a subdirectory within the main “libraries” directory, or within your personal application/libraries directory. The subdirectory must match the parent class name. Read the Drivers description for details.
Additionally, multiple driver libraries can be loaded at the same time by passing an array of drivers to the load method.
$this->load->driver(array(’session’, ’cache’));
498
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Setting options
The second (optional) parameter allows you to optionally pass configuration settings. You will typically pass these as
an array:
$config = array(
’sess_driver’ => ’cookie’,
’sess_encrypt_cookie’ => true,
’encryption_key’ => ’mysecretkey’
);
$this->load->driver(’session’, $config);
Config options can usually also be set via a config file. Each library is explained in detail in its own page, so please
read the information regarding each one you would like to use.
Assigning a Driver to a different object name
If the third (optional) parameter is blank, the library will be assigned to an object with the same name as the parent
class. For example, if the library is named Session, it will be assigned to a variable named $this->session.
If you prefer to set your own class names you can pass its value to the third parameter:
$this->load->library(’session’, ’’, ’my_session’);
// Session class is now accessed using:
$this->my_session
: Driver libraries may also be loaded with the library() method, but it is faster to use driver().
$this->load->view(‘file_name’, $data, TRUE/FALSE)
This method is used to load your View files. If you haven’t read the Views section of the user guide it is recommended
that you do since it shows you how this method is typically used.
The first parameter is required. It is the name of the view file you would like to load.
: The .php file extension does not need to be specified unless you use something other than .php.
The second optional parameter can take an associative array or an object as input, which it runs through the PHP
extract() function to convert to variables that can be used in your view files. Again, read the Views page to learn how
this might be useful.
The third optional parameter lets you change the behavior of the method so that it returns data as a string rather than
sending it to your browser. This can be useful if you want to process the data in some way. If you set the parameter to
true (boolean) it will return data. The default behavior is false, which sends it to your browser. Remember to assign it
to a variable if you want the data returned:
$string = $this->load->view(’myfile’, ’’, true);
10.13. Libraries
499
CodeIgniter Documentation, 3.0-dev
$this->load->model(‘model_name’);
$this->load->model(’model_name’);
If your model is located in a subdirectory, include the relative path from your models directory. For example, if you
have a model located at application/models/blog/Queries.php you’ll load it using:
$this->load->model(’blog/queries’);
If you would like your model assigned to a different object name you can specify it via the second parameter of the
loading method:
$this->load->model(’model_name’, ’fubar’);
$this->fubar->method();
$this->load->database(‘options’, TRUE/FALSE)
This method lets you load the database class. The two parameters are optional. Please see the database section for
more info.
$this->load->vars($array)
This method takes an associative array as input and generates variables using the PHP extract method. This method
produces the same result as using the second parameter of the $this->load->view() method above. The reason
you might want to use this method independently is if you would like to set some global variables in the constructor
of your controller and have them become available in any view file loaded from any method. You can have multiple
calls to this method. The data get cached and merged into one array for conversion to variables.
$this->load->get_var($key)
This method checks the associative array of variables available to your views. This is useful if for any reason a var is
set in a library or another controller method using $this->load->vars().
$this->load->get_vars()
This method retrieves all variables available to your views.
$this->load->clear_vars()
Clears cached view variables.
$this->load->helper(‘file_name’)
This method loads helper files, where file_name is the name of the file, without the _helper.php extension.
$this->load->file(‘filepath/filename’, TRUE/FALSE)
This is a generic file loading method. Supply the filepath and name in the first parameter and it will open and read
the file. By default the data is sent to your browser, just like a View file, but if you set the second parameter to true
(boolean) it will instead return the data as a string.
500
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$this->load->language(‘file_name’)
This method is an alias of the language loading method: $this->lang->load()
$this->load->config(‘file_name’)
This method is an alias of the config file loading method: $this->config->load()
$this->load->is_loaded(‘library_name’)
The is_loaded() method allows you to check if a class has already been loaded or not.
: The word “class” here refers to libraries and drivers.
If the requested class has been loaded, the method returns its assigned name in the CI Super-object and FALSE if it’s
not:
$this->load->library(’form_validation’);
$this->load->is_loaded(’Form_validation’);
// returns ’form_validation’
$this->load->is_loaded(’Nonexistent_library’);
// returns FALSE
: If you have more than one instance of a class (assigned to different properties), then the first one will be returned.
$this->load->library(’form_validation’, $config, ’fv’);
$this->load->library(’form_validation’);
$this->load->is_loaded(’Form_validation’);
// returns ’fv’
Application “Packages”
An application package allows for the easy distribution of complete sets of resources in a single directory, complete
with its own libraries, models, helpers, config, and language files. It is recommended that these packages be placed in
the application/third_party directory. Below is a sample map of an package directory
Sample Package “Foo Bar” Directory Map
The following is an example of a directory for an application package named “Foo Bar”.
/application/third_party/foo_bar
config/
helpers/
language/
libraries/
models/
Whatever the purpose of the “Foo Bar” application package, it has its own config files, helpers, language files, libraries,
and models. To use these resources in your controllers, you first need to tell the Loader that you are going to be loading
resources from a package, by adding the package path.
10.13. Libraries
501
CodeIgniter Documentation, 3.0-dev
$this->load->add_package_path()
Adding a package path instructs the Loader class to prepend a given path for subsequent requests for resources. As
an example, the “Foo Bar” application package above has a library named Foo_bar.php. In our controller, we’d do the
following:
$this->load->add_package_path(APPPATH.’third_party/foo_bar/’);
$this->load->library(’foo_bar’);
$this->load->remove_package_path()
When your controller is finished using resources from an application package, and particularly if you have other
application packages you want to work with, you may wish to remove the package path so the Loader no longer looks
in that directory for resources. To remove the last path added, simply call the method with no parameters.
$this->load->remove_package_path()
Or to remove a specific package path, specify the same path previously given to add_package_path() for a package.:
$this->load->remove_package_path(APPPATH.’third_party/foo_bar/’);
Package view files
By Default, package view files paths are set when add_package_path() is called. View paths are looped through, and
once a match is encountered that view is loaded.
In this instance, it is possible for view naming collisions within packages to occur, and possibly the incorrect package
being loaded. To ensure against this, set an optional second parameter of FALSE when calling add_package_path().
$this->load->add_package_path(APPPATH.’my_app’, FALSE);
$this->load->view(’my_app_index’); // Loads
$this->load->view(’welcome_message’); // Will not load the default welcome_message b/c the second par
// Reset things
$this->load->remove_package_path(APPPATH.’my_app’);
// Again without the second parameter:
$this->load->add_package_path(APPPATH.’my_app’);
$this->load->view(’my_app_index’); // Loads
$this->load->view(’welcome_message’); // Loads
10.13.16 Migrations Class
Migrations are a convenient way for you to alter your database in a structured and organized manner. You could edit
fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run
them. You would also have to keep track of which changes need to be run against the production machines next time
you deploy.
The database table migration tracks which migrations have already been run so all you have to do is update your
application files and call $this->migration->current() to work out which migrations should be run. The current
version is found in config/migration.php.
502
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Migration file names
Each Migration is run in numeric order forward or backwards depending on the method taken. Two numbering styles
are available:
• Sequential: each migration is numbered in sequence, starting with 001. Each number must be three digits, and
there must not be any gaps in the sequence. (This was the numbering scheme prior to CodeIgniter 3.0.)
• Timestamp: each migration is numbered using the timestamp when the migration was created, in YYYYMMDDHHIISS format (e.g. 20121031100537). This helps prevent numbering conflicts when working in a team
environment, and is the preferred scheme in CodeIgniter 3.0 and later.
The desired style may be selected using the $config[’migration_type’] setting in your migration.php config file.
Regardless of which numbering style you choose to use, prefix your migration files with the migration number followed
by an underscore and a descriptive name for the migration. For example:
• 001_add_blog.php (sequential numbering)
• 20121031100537_add_blog.php (timestamp numbering)
Create a Migration
This will be the first migration for a new site which has a blog. All migrations go in the folder application/migrations/
and have names such as 20121031100537_add_blog.php.:
<?php
defined(’BASEPATH’) OR exit(’No direct script access allowed’);
class Migration_Add_blog extends CI_Migration {
public function up()
{
$this->dbforge->add_field(array(
’blog_id’ => array(
’type’ => ’INT’,
’constraint’ => 5,
’unsigned’ => TRUE,
’auto_increment’ => TRUE
),
’blog_title’ => array(
’type’ => ’VARCHAR’,
’constraint’ => ’100’,
),
’blog_description’ => array(
’type’ => ’TEXT’,
’null’ => TRUE,
),
));
$this->dbforge->add_key(’blog_id’, TRUE);
$this->dbforge->create_table(’blog’);
}
public function down()
{
$this->dbforge->drop_table(’blog’);
}
}
10.13. Libraries
503
CodeIgniter Documentation, 3.0-dev
Then in application/config/migration.php set $config[’migration_version’] = 1;.
Usage Example
In this example some simple code is placed in application/controllers/Migrate.php to update the schema.:
<?php
class Migrate extends CI_Controller
{
public function index()
{
$this->load->library(’migration’);
if ($this->migration->current() === FALSE)
{
show_error($this->migration->error_string());
}
}
}
Function Reference
$this->migration->current()
The current migration is whatever is set for $config[’migration_version’] in application/config/migration.php.
$this->migration->error_string()
This returns a string of errors while performing a migration.
$this->migration->find_migrations()
An array of migration filenames are returned that are found in the migration_path property.
$this->migration->latest()
This works much the same way as current() but instead of looking for the $config[’migration_version’] the Migration
class will use the very newest migration found in the filesystem.
$this->migration->version()
Version can be used to roll back changes or step forwards programmatically to specific versions. It works just like
current but ignores $config[’migration_version’].:
$this->load->library(’migration’);
$this->migration->version(5);
504
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Migration Preferences
The following is a table of all the config options for migrations.
Preference
migration_enabled
migration_path
migration_version
migration_table
migration_auto_latest
migration_type
Default
FALSE
Options
TRUE / FALSE
Description
Enable or disable migrations.
APPPATH.’migrations/’
0
None
The path to your migrations folder.
None
The current version your database should use.
migrations
None
FALSE
TRUE / FALSE
‘timestamp’
‘timestamp’ /
‘sequential’
The table name for storing the schema version
number.
Enable or disable automatically running
migrations.
The type of numeric identifier used to name
migration files.
10.13.17 Output Class
The Output class is a small class with one main function: To send the finalized web page to the requesting browser. It
is also responsible for caching your web pages, if you use that feature.
: This class is initialized automatically by the system so there is no need to do it manually.
Under normal circumstances you won’t even notice the Output class since it works transparently without your intervention. For example, when you use the Loader class to load a view file, it’s automatically passed to the Output class,
which will be called automatically by CodeIgniter at the end of system execution. It is possible, however, for you to
manually intervene with the output if you need to, using either of the two following functions:
$this->output->set_output();
Permits you to manually set the final output string. Usage example:
$this->output->set_output($data);
: If you do set your output manually, it must be the last thing done in the function you call it from. For example, if
you build a page in one of your controller functions, don’t set the output until the end.
$this->output->set_content_type();
Permits you to set the mime-type of your page so you can serve JSON data, JPEG’s, XML, etc easily.
$this->output
->set_content_type(’application/json’)
->set_output(json_encode(array(’foo’ => ’bar’)));
$this->output
->set_content_type(’jpeg’) // You could also use ".jpeg" which will have the full stop removed be
->set_output(file_get_contents(’files/something.jpg’));
10.13. Libraries
505
CodeIgniter Documentation, 3.0-dev
: Make sure any non-mime string you pass to this method exists in config/mimes.php or it will have no effect.
You can also set the character set of the document, by passing a second argument:
$this->output->set_content_type(’css’, ’utf-8’);
$this->output->get_content_type()
Returns the Content-Type HTTP header that’s currently in use, excluding the character set value.
$mime = $this->output->get_content_type();
: If not set, the default return value is ‘text/html’.
$this->output->get_header()
Gets the requested HTTP header value, if set.
If the header is not set, NULL will be returned. If an empty value is passed to the method, it will return FALSE.
Example:
$this->output->set_content_type(’text/plain’, ’UTF-8’);
echo $this->output->get_header(’content-type’);
// Outputs: text/plain; charset=utf-8
: The header name is compared in a case-insensitive manner.
: Raw headers sent via PHP’s native header() function are also detected.
$this->output->get_output()
Permits you to manually retrieve any output that has been sent for storage in the output class. Usage example:
$string = $this->output->get_output();
Note that data will only be retrievable from this function if it has been previously sent to the output class by one of the
CodeIgniter functions like $this->load->view().
$this->output->append_output();
Appends data onto the output string. Usage example:
$this->output->append_output($data);
$this->output->set_header();
Permits you to manually set server headers, which the output class will send for you when outputting the final rendered
display. Example:
506
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$this->output->set_header("HTTP/1.0 200 OK");
$this->output->set_header("HTTP/1.1 200 OK");
$this->output->set_header(’Last-Modified: ’.gmdate(’D, d M Y H:i:s’, $last_update).’ GMT’);
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
$this->output->set_header("Cache-Control: post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
$this->output->set_status_header(code, ‘text’);
Permits you to manually set a server status header. Example:
$this->output->set_status_header(’401’);
// Sets the header as: Unauthorized
See here for a full list of headers.
: This method is an alias for Common function set_status_header().
$this->output->enable_profiler();
Permits you to enable/disable the Profiler, which will display benchmark and other data at the bottom of your pages
for debugging and optimization purposes.
To enable the profiler place the following function anywhere within your Controller functions:
$this->output->enable_profiler(TRUE);
When enabled a report will be generated and inserted at the bottom of your pages.
To disable the profiler you will use:
$this->output->enable_profiler(FALSE);
$this->output->set_profiler_sections();
Permits you to enable/disable specific sections of the Profiler when enabled. Please refer to the Profiler documentation
for further information.
$this->output->cache();
The CodeIgniter output library also controls caching. For more information, please see the caching documentation.
Parsing Execution Variables
CodeIgniter will parse the pseudo-variables {elapsed_time} and {memory_usage} in your output by default. To disable
this, set the $parse_exec_vars class property to FALSE in your controller.
$this->output->parse_exec_vars = FALSE;
10.13. Libraries
507
CodeIgniter Documentation, 3.0-dev
10.13.18 Pagination Class
CodeIgniter’s Pagination class is very easy to use, and it is 100% customizable, either dynamically or via stored
preferences.
If you are not familiar with the term “pagination”, it refers to links that allows you to navigate from page to page, like
this:
« First
< 1 2 3 4 5 >
Last »
Example
Here is a simple example showing how to create pagination in one of your controller functions:
$this->load->library(’pagination’);
$config[’base_url’] = ’http://example.com/index.php/test/page/’;
$config[’total_rows’] = 200;
$config[’per_page’] = 20;
$this->pagination->initialize($config);
echo $this->pagination->create_links();
Notes
The $config array contains your configuration variables. It is passed to the $this->pagination->initialize function as
shown above. Although there are some twenty items you can configure, at minimum you need the three shown. Here
is a description of what those items represent:
• base_url This is the full URL to the controller class/function containing your pagination. In the example above,
it is pointing to a controller called “Test” and a function called “page”. Keep in mind that you can re-route your
URI if you need a different structure.
• total_rows This number represents the total rows in the result set you are creating pagination for. Typically this
number will be the total rows that your database query returned.
• per_page The number of items you intend to show per page. In the above example, you would be showing 20
items per page.
The create_links() function returns an empty string when there is no pagination to show.
Setting preferences in a config file
If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create
a new file called pagination.php, add the $config array in that file. Then save the file in: config/pagination.php and
it will be used automatically. You will NOT need to use the $this->pagination->initialize function if you save your
preferences in a config file.
Customizing the Pagination
The following is a list of all the preferences you can pass to the initialization function to tailor the display.
508
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
$config[’uri_segment’] = 3;
The pagination function automatically determines which segment of your URI contains the page number. If you need
something different you can specify it.
$config[’num_links’] = 2;
The number of “digit” links you would like before and after the selected page number. For example, the number 2 will
place two digits on either side, as in the example links at the very top of this page.
$config[’use_page_numbers’] = TRUE;
By default, the URI segment will use the starting index for the items you are paginating. If you prefer to show the the
actual page number, set this to TRUE.
$config[’page_query_string’] = TRUE;
By default, the pagination library assume you are using URI Segments, and constructs your links something like
http://example.com/index.php/test/page/20
If you have $config[’enable_query_strings’] set to TRUE your links will automatically be re-written using Query
Strings. This option can also be explictly set. Using $config[’page_query_string’] set to TRUE, the pagination link
will become.
http://example.com/index.php?c=test&m=page&per_page=20
Note that “per_page” is the default query string passed,
fig[’query_string_segment’] = ‘your_string’
however can be configured using $con-
$config[’reuse_query_string’] = FALSE;
By default your Query String arguments (nothing to do with other query string options) will be ignored. Setting this
config to TRUE will add existing query string arguments back into the URL after the URI segment and before the
suffix
http://example.com/index.php/test/page/20?query=search%term
This helps you mix together normal URI Segments as well as query string arguments, which until 3.0 was not possible.
$config[’prefix’] = ‘’;
A custom prefix added to the path. The prefix value will be right before the offset segment.
$config[’suffix’] = ‘’;
A custom suffix added to the path. The sufix value will be right after the offset segment.
10.13. Libraries
509
CodeIgniter Documentation, 3.0-dev
Adding Enclosing Markup
If you would like to surround the entire pagination with some markup you can do it with these two prefs:
$config[’full_tag_open’] = ‘<p>’;
The opening tag placed on the left side of the entire result.
$config[’full_tag_close’] = ‘</p>’;
The closing tag placed on the right side of the entire result.
Customizing the First Link
$config[’first_link’] = ‘First’;
The text you would like shown in the “first” link on the left. If you do not want this link rendered, you can set its value
to FALSE.
$config[’first_tag_open’] = ‘<div>’;
The opening tag for the “first” link.
$config[’first_tag_close’] = ‘</div>’;
The closing tag for the “first” link.
Customizing the Last Link
$config[’last_link’] = ‘Last’;
The text you would like shown in the “last” link on the right. If you do not want this link rendered, you can set its
value to FALSE.
$config[’last_tag_open’] = ‘<div>’;
The opening tag for the “last” link.
$config[’last_tag_close’] = ‘</div>’;
The closing tag for the “last” link.
510
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Customizing the “Next” Link
$config[’next_link’] = ‘&gt;’;
The text you would like shown in the “next” page link. If you do not want this link rendered, you can set its value to
FALSE.
$config[’next_tag_open’] = ‘<div>’;
The opening tag for the “next” link.
$config[’next_tag_close’] = ‘</div>’;
The closing tag for the “next” link.
Customizing the “Previous” Link
$config[’prev_link’] = ‘&lt;’;
The text you would like shown in the “previous” page link. If you do not want this link rendered, you can set its value
to FALSE.
$config[’prev_tag_open’] = ‘<div>’;
The opening tag for the “previous” link.
$config[’prev_tag_close’] = ‘</div>’;
The closing tag for the “previous” link.
Customizing the “Current Page” Link
$config[’cur_tag_open’] = ‘<b>’;
The opening tag for the “current” link.
$config[’cur_tag_close’] = ‘</b>’;
The closing tag for the “current” link.
Customizing the “Digit” Link
$config[’num_tag_open’] = ‘<div>’;
The opening tag for the “digit” link.
10.13. Libraries
511
CodeIgniter Documentation, 3.0-dev
$config[’num_tag_close’] = ‘</div>’;
The closing tag for the “digit” link.
Hiding the Pages
If you wanted to not list the specific pages (for example, you only want “next” and “previous” links), you can suppress
their rendering by adding:
$config[’display_pages’] = FALSE;
Adding attributes to anchors
If you want to add an extra attribute to be added to every link rendered by the pagination class, you can set them as
key/value pairs in the “attributes” config
// Produces: class="myclass"
$config[’attributes’] = array(’class’ => ’myclass’);
: Usage of the old method of setting classes via “anchor_class” is deprecated.
Disabling the “rel” attribute
By default the rel attribute is dynamically generated and appended to the appropriate anchors. If for some reason you
want to turn it off, you can pass boolean FALSE as a regular attribute
$config[’attributes’][’rel’] = FALSE;
10.13.19 Template Parser Class
The Template Parser Class enables you to parse pseudo-variables contained within your view files. It can parse simple
variables or variable tag pairs. If you’ve never used a template engine, pseudo-variables look like this:
<html>
<head>
<title>{blog_title}</title>
</head>
<body>
<h3>{blog_heading}</h3>
{blog_entries}
<h5>{title}</h5>
<p>{body}</p>
{/blog_entries}
</body>
</html>
These variables are not actual PHP variables, but rather plain text representations that allow you to eliminate PHP
from your templates (view files).
: CodeIgniter does not require you to use this class since using pure PHP in your view pages lets them run a little
512
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
faster. However, some developers prefer to use a template engine if they work with designers who they feel would find
some confusion working with PHP.
: The Template Parser Class is not a full-blown template parsing solution. We’ve kept it very lean on purpose in order
to maintain maximum performance.
Initializing the Class
Like most other classes in CodeIgniter, the Parser class is initialized in your controller using the $this->load->library
function:
$this->load->library(’parser’);
Once loaded, the Parser library object will be available using: $this->parser
The following functions are available in this library:
$this->parser->parse()
This method accepts a template name and data array as input, and it generates a parsed version. Example:
$this->load->library(’parser’);
$data = array(
’blog_title’ => ’My Blog Title’,
’blog_heading’ => ’My Blog Heading’
);
$this->parser->parse(’blog_template’, $data);
The first parameter contains the name of the view file (in this example the file would be called blog_template.php), and
the second parameter contains an associative array of data to be replaced in the template. In the above example, the
template would contain two variables: {blog_title} and {blog_heading}
There is no need to “echo” or do something with the data returned by $this->parser->parse(). It is automatically passed
to the output class to be sent to the browser. However, if you do want the data returned instead of sent to the output
class you can pass TRUE (boolean) to the third parameter:
$string = $this->parser->parse(’blog_template’, $data, TRUE);
$this->parser->parse_string()
This method works exactly like parse(), only accepts a string as the first parameter in place of a view file.
Variable Pairs
The above example code allows simple variables to be replaced. What if you would like an entire block of variables
to be repeated, with each iteration containing new values? Consider the template example we showed at the top of the
page:
10.13. Libraries
513
CodeIgniter Documentation, 3.0-dev
<html>
<head>
<title>{blog_title}</title>
</head>
<body>
<h3>{blog_heading}</h3>
{blog_entries}
<h5>{title}</h5>
<p>{body}</p>
{/blog_entries}
</body>
</html>
In the above code you’ll notice a pair of variables: {blog_entries} data... {/blog_entries}. In a case like this, the entire
chunk of data between these pairs would be repeated multiple times, corresponding to the number of rows in a result.
Parsing variable pairs is done using the identical code shown above to parse single variables, except, you will add a
multi-dimensional array corresponding to your variable pair data. Consider this example:
$this->load->library(’parser’);
$data = array(
’blog_title’
=> ’My Blog Title’,
’blog_heading’ => ’My Blog Heading’,
’blog_entries’ => array(
array(’title’
array(’title’
array(’title’
array(’title’
array(’title’
)
);
=>
=>
=>
=>
=>
’Title
’Title
’Title
’Title
’Title
1’,
2’,
3’,
4’,
5’,
’body’
’body’
’body’
’body’
’body’
=>
=>
=>
=>
=>
’Body
’Body
’Body
’Body
’Body
1’),
2’),
3’),
4’),
5’)
$this->parser->parse(’blog_template’, $data);
If your “pair” data is coming from a database result, which is already a multi-dimensional array, you can simply use
the database result_array() function:
$query = $this->db->query("SELECT * FROM blog");
$this->load->library(’parser’);
$data = array(
’blog_title’
=> ’My Blog Title’,
’blog_heading’ => ’My Blog Heading’,
’blog_entries’ => $query->result_array()
);
$this->parser->parse(’blog_template’, $data);
10.13.20 Security Class
The Security Class contains methods that help you create a secure application, processing input data for security.
514
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
XSS Filtering
CodeIgniter comes with a Cross Site Scripting Hack prevention filter which can either run automatically to filter all
POST and COOKIE data that is encountered, or you can run it on a per item basis. By default it does not run globally
since it requires a bit of processing overhead, and since you may not need it in all cases.
The XSS filter looks for commonly used techniques to trigger Javascript or other types of code that attempt to hijack
cookies or do other malicious things. If anything disallowed is encountered it is rendered safe by converting the data
to character entities.
Note: This function should only be used to deal with data upon submission. It’s not something that should be used for
general runtime processing since it requires a fair amount of processing overhead.
To filter data through the XSS filter use this function:
$this->security->xss_clean()
Here is an usage example:
$data = $this->security->xss_clean($data);
If you want the filter to run automatically every time it encounters POST or COOKIE data you can enable it by opening
your application/config/config.php file and setting this:
$config[’global_xss_filtering’] = TRUE;
Note: If you use the form validation class, it gives you the option of XSS filtering as well.
An optional second parameter, is_image, allows this function to be used to test images for potential XSS attacks, useful
for file upload security. When this second parameter is set to TRUE, instead of returning an altered string, the function
returns TRUE if the image is safe, and FALSE if it contained potentially malicious information that a browser may
attempt to execute.
if ($this->security->xss_clean($file, TRUE) === FALSE)
{
// file failed the XSS test
}
$this->security->sanitize_filename()
When accepting filenames from user input, it is best to sanitize them to prevent directory traversal and other security
related issues. To do so, use the sanitize_filename() method of the Security class. Here is an example:
$filename = $this->security->sanitize_filename($this->input->post(’filename’));
If it is acceptable for the user input to include relative paths, e.g. file/in/some/approved/folder.txt, you can set the
second optional parameter, $relative_path to TRUE.
$filename = $this->security->sanitize_filename($this->input->post(’filename’), TRUE);
Cross-site request forgery (CSRF)
You can enable CSRF protection by opening your application/config/config.php file and setting this:
$config[’csrf_protection’] = TRUE;
10.13. Libraries
515
CodeIgniter Documentation, 3.0-dev
If you use the form helper, then form_open() will automatically insert a hidden csrf field in your forms. If not,
then you can use csrf_get_token_name() and csrf_get_hash()
$csrf = array(
’name’ => $this->security->csrf_get_token_name(),
’hash’ => $this->security->csrf_get_hash()
);
...
<input type="hidden" name="<?=$csrf[’name’];?>" value="<?=$csrf[’hash’];?>" />
Tokens may be either regenerated on every submission (default) or kept the same throughout the life of the CSRF
cookie. The default regeneration of tokens provides stricter security, but may result in usability concerns as other
tokens become invalid (back/forward navigation, multiple tabs/windows, asynchronous actions, etc). You may alter
this behavior by editing the following config parameter
$config[’csrf_regeneration’] = TRUE;
Select URIs can be whitelisted from csrf protection (for example API endpoints expecting externally POSTed content).
You can add these URIs by editing the ‘csrf_exclude_uris’ config parameter:
$config[’csrf_exclude_uris’] = array(’api/person/add’);
$this->security->get_csrf_token_name()
Returns the CSRF token name, which is set by $config[’csrf_token_name’].
$this->security->get_csrf_hash()
Returns the CSRF hash value. Useful in combination with get_csrf_token_name() for manually building
forms or sending valid AJAX POST requests.
10.13.21 Session Driver
The Session class permits you maintain a user’s “state” and track their activity while they browse your site. CodeIgniter
offers two default session drivers: the classic Cookie Driver, and the Native Driver, which supports usage of the native
PHP Session mechanism. In addition, you may create your own Custom Drivers to store session data however you
wish, while still taking advantage of the features of the Session class.
Initializing a Session
Sessions will typically run globally with each page load, so the session class must either be initialized in your controller
constructors, or it can be auto-loaded by the system. For the most part the session class will run unattended in the
background, so simply initializing the class will cause it to read, create, and update sessions.
To initialize the Session class manually in your controller constructor, use the $this->load->driver function:
$this->load->driver(’session’);
Once loaded, the Sessions library object will be available using: $this->session
516
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
How do Sessions work?
When a page is loaded, the session class will check to see if valid session data exists in the user’s session. If sessions
data does not exist (or if it has expired) a new session will be created and saved. If a session does exist, its information
will be updated. With each update, the session_id will be regenerated.
It’s important for you to understand that once initialized, the Session class runs automatically. There is nothing you
need to do to cause the above behavior to happen. You can, as you’ll see below, work with session data or even add
your own data to a user’s session, but the process of reading, writing, and updating a session is automatic.
What is Session Data?
A session, as far as CodeIgniter is concerned, is simply an array containing the following information:
• The user’s unique Session ID (this is a statistically random string with very strong entropy, hashed with MD5
for portability, and regenerated (by default) every five minutes)
• The user’s IP Address
• The user’s User Agent data (the first 120 characters of the browser data string)
• The “last activity” time stamp.
The above data is stored in a cookie as a serialized array with this prototype:
[array]
(
’session_id’
’ip_address’
’user_agent’
’last_activity’
)
=>
=>
=>
=>
random hash,
’string - user IP address’,
’string - user agent data’,
timestamp
: Sessions are only updated every five minutes by default to reduce processor load. If you repeatedly reload a
page you’ll notice that the “last activity” time only updates if five minutes or more has passed since the last time
the cookie was written. This time is configurable by changing the $config[’sess_time_to_update’] line in your system/config/config.php file.
Retrieving Session Data
Any piece of information from the session array is available using the following function:
$this->session->userdata(’item’);
Where item is the array index corresponding to the item you wish to fetch. For example, to fetch the session ID you
will do this:
$session_id = $this->session->userdata(’session_id’);
: The function returns NULL if the item you are trying to access does not exist.
Adding Custom Session Data
A useful aspect of the session array is that you can add your own data to it and it will be stored in the user’s cookie.
Why would you want to do this? Here’s one example:
10.13. Libraries
517
CodeIgniter Documentation, 3.0-dev
Let’s say a particular user logs into your site. Once authenticated, you could add their username and email address to
the session, making that data globally available to you without having to run a database query when you need it.
To add your data to the session array involves passing an array containing your new data to this function:
$this->session->set_userdata($array);
Where $array is an associative array containing your new data. Here’s an example:
$newdata = array(
’username’ => ’johndoe’,
’email’
=> ’johndoe@some-site.com’,
’logged_in’ => TRUE
);
$this->session->set_userdata($newdata);
If you want to add userdata one value at a time, set_userdata() also supports this syntax.
$this->session->set_userdata(’some_name’, ’some_value’);
If you want to verify that a userdata value exists, call has_userdata().
$this->session->has_userdata(’some_name’);
Retrieving All Session Data
An array of all userdata can be retrieved as follows:
$this->session->all_userdata()
And returns an associative array like the following:
Array
(
[session_id] =>
[ip_address] =>
[user_agent] =>
[last_activity]
)
4a5a5dca22728fb0a84364eeb405b601
127.0.0.1
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7;
=> 1303142623
Removing Session Data
Just as set_userdata() can be used to add information into a session, unset_userdata() can be used to remove it, by
passing the session key. For example, if you wanted to remove ‘some_name’ from your session information:
$this->session->unset_userdata(’some_name’);
This function can also be passed an associative array of items to unset.
$array_items = array(’username’ => ’’, ’email’ => ’’);
$this->session->unset_userdata($array_items);
518
Chapter 10. CodeIgniter
CodeIgniter Documentation, 3.0-dev
Flashdata
CodeIgniter supports “flashdata”, or session data that will only be available for the next server request, and are then
automatically cleared. These can be very useful, and are typically used for informational or status messages (for
example: “record 2 deleted”).
: Flash variables are prefaced with “flash_” so avoid this prefix in your own session names.
To add flashdata:
$this->session->set_flashdata(’item’, ’value’);
You can also pass an array to set_flashdata(), in the same manner as set_userdata().
To read a flashdata variable:
$this->session->flashdata(’item’);
An array of all flashdata can be retrieved as follows:
$this->session->all_flashdata();
If you find that you need to preserve a flashdata variable through an additional request, you can do so using the
keep_flashdata() function. You can either pass a single item or an array of flashdata items to keep.
$this->session->keep_flashdata(’item’);
$this->session->keep_flashdata(array(’item1’, ’item2’, ’item3’));
Tempdata
CodeIgniter also supports “tempdata”, or session data with a specific expiration time. After the value expires, or the
session expires or is deleted, the value is automatically removed.
To add tempdata:
$expire = 300;
// Expire in 5 minutes
$this->session->set_tempdata(’item’, ’value’, $expire);
You can also pass an array to set_tempdata():
$tempdata = array(’newuser’ => TRUE, ’message’ => ’Thanks for joining!’);
$this->session->set_tempdata($tempdata, ’’, $expire);
: If the expiration is omitted or set to 0, the default expiration of 5 minutes will be used.
To read a tempdata variable:
$this->session->tempdata(’item’);
If you need to remove a tempdata value before it expires, use unset_tempdata():
$this->session->unset_tempdata(’item’);
10.13. Libraries
519
CodeIgniter Documentation, 3.0-dev
Destroying a Session
To clear the current session:
$this->session->sess_destroy();
: This function should be the last one called, and even flash variables will no longer be available. If you only want
some items destroyed and not all, use unset_userdata().
Session Preferences
You’ll find the following Session related preferences in your application/config/config.php file:
PreferDeOptions
Description
ence
fault
sess_driver cookie cookie/native/custom
The initial session driver to load.
sess_valid_drivers
cookie, None
Additional valid drivers which may be loaded.
native
sess_cookie_name
ci_sessionNone
The name you want the session cookie saved as (data for Cookie driver or
session ID for Native driver).
sess_expiration
7200
None
The number of seconds you would like the session to last. The default value
is 2 hours (7200 seconds). If you would like a non-expiring session set the
value to zero: 0
sess_expire_on_close
FALSE TRUE/FALSE Whether to cause the session to expire automatically when the browser
(boolean)
window is closed.
sess_encrypt_cookie
FALSE TRUE/FALSE Whether to encrypt the session data (Cookie driver only).
(boolean)
sess_use_database
FALSE TRUE/FALSE Whether to save the session data to a database. You must create the table
(boolean)
before enabling this option (Cookie driver only).
sess_table_name
ci_sessions
Any valid
The name of the session database table (Cookie driver only).
SQL table
name
sess_time_to_update
300
Time in
This options controls how often the session class will regenerate itself and
seconds
create a new session ID. Setting it to 0 will disable session ID regeneartion.
sess_match_ip
FALSE TRUE/FALSE Whether to match the user’s IP address when reading the session data. Note
(boolean)
that some ISPs dynamically changes the IP, so if you want a non-expiring
session you will likely set this to FALSE.
sess_match_useragent
TRUE TRUE/FALSE Whether to match the User Agent when reading the session data.
(boolean)
In addition to the values above, the cookie and native drivers apply the following configuration values shared by the
Input and Security classes:
Preference
cookie_prefix
cookie_domai