CodeIgniter - Overview
CodeIgniter 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
- 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
CodeIgniter - Installing
- Step-1 − Download the CodeIgniter from the link CodeIgniter
- Step-2 − Unzip the folder.
- Step-3 − Upload all files and folders to your server.
- Step-4 − After uploading all the files to your server, visit the URL of your server, e.g., www.domain-name.com.
CodeIgniter - Application Architecture
- As shown in the figure, whenever a request comes to CodeIgniter, it will first go to index.php page.
- In the second step, Routing will decide whether to pass this request to step-3 for caching or to pass this request to step-4 for security check.
- If the requested page is already in Caching, then Routing will pass the request to step-3 and the response will go back to the user.
- If the requested page does not exist in Caching, then Routing will pass the requested page to step-4 for Security checks.
- Before passing the request to Application Controller, the Securityof the submitted data is checked. After the Security check, the Application Controller loads necessary Models, Libraries, Helpers, Plugins and Scripts and pass it on to View.
- The View will render the page with available data and pass it on for Caching. As the requested page was not cached before so this time it will be cached in Caching, to process this page quickly for future requests.
Directory Structure
- Application
- System
- User_guide
Application
- Cache − This folder contains all the cached pages of your application. These cached pages will increase the overall speed of accessing the pages.
- Config − This folder contains various files to configure the application. With the help of config.php file, user can configure the application. Using database.php file, user can configure the database of the application.
- Controllers − This folder holds the controllers of your application. It is the basic part of your application.
- Core − This folder will contain base class of your application.
- Helpers − In this folder, you can put helper class of your application.
- Hooks − The files in this folder provide a means to tap into and modify the inner workings of the framework without hacking the core files.
- Language − This folder contains language related files.
- Libraries − This folder contains files of the libraries developed for your application.
- Logs − This folder contains files related to the log of the system.
- Models − The database login will be placed in this folder.
- Third_party − In this folder, you can place any plugins, which will be used for your application.
- Views − Application’s HTML files will be placed in this folder.
System
- Core − This folder contains CodeIgniter’s core class. Do not modify anything here. All of your work will take place in the application folder. Even if your intent is to extend the CodeIgniter core, you have to do it with hooks, and hooks live in the application folder.
- Database − The database folder contains core database drivers and other database utilities.
- Fonts − The fonts folder contains font related information and utilities.
- Helpers − The helpers folder contains standard CodeIgniter helpers (such as date, cookie, and URL helpers).
- Language − The language folder contains language files. You can ignore it for now.
- Libraries − The libraries folder contains standard CodeIgniter libraries (to help you with e-mail, calendars, file uploads, and more). You can create your own libraries or extend (and even replace) standard ones, but those will be saved in the application/libraries directory to keep them separate from the standard CodeIgniter libraries saved in this particular folder.
User_guide
CodeIgniter - MVC Framework
- 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 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.
CodeIgniter - Basic Concepts
Controllers
Creating a Controller
<?php
class Test extends CI_Controller {
public function index() {
echo "Hello World!";
}
}
?>
Calling a Controller
http://www.your-domain.com/index.php/test
http://www.your-domain.com/index.php/controller/method-name
Creating & Calling Constructor Method
<?php
class Test extends CI_Controller {
public function index() {
echo "This is default function.";
}
public function hello() {
echo "This is hello function.";
}
}
?>
- http://www.your-domain.com/index.php/test
- http://www.your-domain.com/index.php/test/index
- http://www.your-domain.com/index.php/test/hello
Points to Remember
- The name of the controller class must start with an uppercase letter.
- The controller must be called with lowercase letter.
- Do not use the same name of the method as your parent class, as it will override parent class’s functionality.
Views
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>
<body>
CodeIgniter View Example
</body>
</html>
Loading the View
$this->load->view('name');
$this->load->view('directory-name/name');
<?php
class Test extends CI_Controller {
public function index() {
$this->load->view('test');
}
}
?>
Models
Creating Model Class
<?php
Class Model_name extends CI_Model {
Public function __construct() {
parent::__construct();
}
}
?>
<?php
Class User_model extends CI_Model {
Public function __construct() {
parent::__construct();
}
}
?>
Loading Model
$this->load->model('model_name');
$this->model_name->method();
Auto-loading Models
/*
| ---------------------------------------------------------------
| Auto-Load Models
| ---------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array();
Helpers
Loading a Helper
$this->load->helper('name');
$this->load->helper('url');
Routing
your-domain.com/class/method/id/
- The first segment represents the controller class that should be invoked.
- The second segment represents the class function, or method, that should be called.
- The third, and any additional segments, represent the ID and any variables that will be passed to the controller.
Customize Routing Rules
| S.N. | Reserved Routes & Description |
|---|---|
| 1 | $route['default_controller'] 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. You are encouraged to have a default route otherwise a 404 page will appear, by default. We can set home page of website here so it will be loaded by default. |
| 2 | $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 in application/views/errors/error_404.php. |
| 3 | $route['translate_uri_dashes'] 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 is not a valid class or method-name character and will cause a fatal error, if you try to use it. |
Wildcards
- (:num) − It will match a segment containing only numbers.
- (:any) − It will match a segment containing any character.
$route['product/:num']='catalog/product_lookup';
Regular Expressions
$route['products/([a-z]+)/(\d+)']='$1/id_$2';
CodeIgniter - Configuration
Configuring Base URL
http://example.com/
$config['base_url'] = 'http://your-domain.com';
Database Configuration
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'database_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array()
);
- hostname − Specify location of your database here e.g. localhost or IP address
- username − Set username of your database here.
- password − Set password of your database here.
- database − Set name of the database here.
- dbdriver − Set type of database that you are using e.g. MySQL, MySQLi, Postgre SQL, ODBC, and MS SQL.
$db['test'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'database_name',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array()
);
Autoload Configuration
- Libraries − It is a list of libraries, which should be auto loaded. Provide a list of libraries in an array as shown below to be autoloaded by CodeIgniter. In this example, we are auto loading database, email and session libraries.
$autoload['libraries'] = array('database', 'email', 'session');
- Drivers − These classes are located in system/libraries/ or in your application/libraries/ directory, but are also placed inside their own subdirectory and they extend the CI_Driver_Library class. They offer multiple interchangeable driver options. Following is an example to autoload cache drivers.
$autoload['drivers'] = array('cache');
- Helper files − It is a list of helper files, to be autoloaded. Provide a list of libraries in the array, as shown below, to be autoloaded by CodeIgniter. In the given example, we are autoloading URL and file helpers.
$autoload['helper'] = array('url', 'file');
- Custom config files − These files are intended for use, only if you have created custom config files. Otherwise, leave it blank. Following is an example of how to autoload more than one config files.
$autoload['config'] = array('config1', 'config2');
- Language files − It is a list of language files, which should be auto loaded. Look at the example given below. Provide a list of languages in an array as shown below to be auto loaded by CodeIgniter. Keep in mind that do not include the "_lang" part of your file. For example, "codeigniter_lang.php" would be referenced as array('codeigniter');
- Models − It is a list of models file, which should be autoloaded. Provide a list of models in an array as shown below to be autoloaded by CodeIgniter. Following is the example of how to auto load more than one models files.
$autoload['model'] = array('first_model', 'second_model');
CodeIgniter - Working with Database
| Table Name: stud | |
|---|---|
| roll_no | int(11) |
| name | varchar(30) |
Connecting to a Database
- Automatic Connecting − Automatic connection can be done by using the file application/config/autoload.php. Automatic connection will load the database for each and every page. We just need to add the database library as shown below −
$autoload['libraries'] = array(‘database’);
- Manual Connecting − If you want database connectivity for only some of the pages, then we can go for manual connecting. We can connect to database manually by adding the following line in any class.
$this->load->database();
Inserting a Record
Syntax | insert([$table = ''[, $set = NULL[, $escape = NULL]]]) |
Parameters |
|
Returns | TRUE on success, FALSE on failure |
Return Type | bool |
$data = array(
'roll_no' => ‘1’,
'name' => ‘Virat’
);
$this->db->insert("stud", $data);
Updating a Record
Syntax | set($key[, $value = ''[, $escape = NULL]]) |
Parameters |
|
Returns | CI_DB_query_builder instance (method chaining) |
Return Type | CI_DB_query_builder |
Syntax | where($key[, $value = NULL[, $escape = NULL]]) |
Parameters |
|
Returns | DB_query_builder instance |
Return Type | object |
Syntax | update([$table = ''[, $set = NULL[, $where = NULL[, $limit = NULL]]]]) |
Parameters |
|
Returns | TRUE on success, FALSE on failure |
Return Type | bool |
$data = array(
'roll_no' => ‘1’,
'name' => ‘Virat’
);
$this->db->set($data);
$this->db->where("roll_no", ‘1’);
$this->db->update("stud", $data);
Deleting a Record
Syntax | delete([$table = ''[, $where = ''[, $limit = NULL[, $reset_data = TRUE]]]]) |
Parameters |
|
Returns | CI_DB_query_builder instance (method chaining) or FALSE on failure |
Return Type | mixed |
$this->db->delete("stud", "roll_no = 1");
Selecting a Record
Syntax | get([$table = ''[, $limit = NULL[, $offset = NULL]]]) |
Parameters |
|
Returns | CI_DB_result instance (method chaining) |
Return Type | CI_DB_result |
$query = $this->db->get("stud");
$data['records'] = $query->result();
Closing a Connection
$this->db->close();
Example
<?php
class Stud_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->database();
}
public function index() {
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->helper('url');
$this->load->view('Stud_view',$data);
}
public function add_student_view() {
$this->load->helper('form');
$this->load->view('Stud_add');
}
public function add_student() {
$this->load->model('Stud_Model');
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name')
);
$this->Stud_Model->insert($data);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function update_student_view() {
$this->load->helper('form');
$roll_no = $this->uri->segment('3');
$query = $this->db->get_where("stud",array("roll_no"=>$roll_no));
$data['records'] = $query->result();
$data['old_roll_no'] = $roll_no;
$this->load->view('Stud_edit',$data);
}
public function update_student(){
$this->load->model('Stud_Model');
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name')
);
$old_roll_no = $this->input->post('old_roll_no');
$this->Stud_Model->update($data,$old_roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function delete_student() {
$this->load->model('Stud_Model');
$roll_no = $this->uri->segment('3');
$this->Stud_Model->delete($roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
}
?>
<?php
class Stud_Model extends CI_Model {
function __construct() {
parent::__construct();
}
public function insert($data) {
if ($this->db->insert("stud", $data)) {
return true;
}
}
public function delete($roll_no) {
if ($this->db->delete("stud", "roll_no = ".$roll_no)) {
return true;
}
}
public function update($data,$old_roll_no) {
$this->db->set($data);
$this->db->where("roll_no", $old_roll_no);
$this->db->update("stud", $data);
}
}
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<form method = "" action = "">
<?php
echo form_open('Stud_controller/add_student');
echo form_label('Roll No.');
echo form_input(array('id'=>'roll_no','name'=>'roll_no'));
echo "<br/>";
echo form_label('Name');
echo form_input(array('id'=>'name','name'=>'name'));
echo "<br/>";
echo form_submit(array('id'=>'submit','value'=>'Add'));
echo form_close();
?>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<form method = "" action = "">
<?php
echo form_open('Stud_controller/update_student');
echo form_hidden('old_roll_no',$old_roll_no);
echo form_label('Roll No.');
echo form_input(array('id'⇒'roll_no',
'name'⇒'roll_no','value'⇒$records[0]→roll_no));
echo "
";
echo form_label('Name');
echo form_input(array('id'⇒'name','name'⇒'name',
'value'⇒$records[0]→name));
echo "
";
echo form_submit(array('id'⇒'sub mit','value'⇒'Edit'));
echo form_close();
?>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<a href = "<?php echo base_url(); ?>
index.php/stud/add_view">Add</a>
<table border = "1">
<?php
$i = 1;
echo "<tr>";
echo "<td>Sr#</td>";
echo "<td>Roll No.</td>";
echo "<td>Name</td>";
echo "<td>Edit</td>";
echo "<td>Delete</td>";
echo "<tr>";
foreach($records as $r) {
echo "<tr>";
echo "<td>".$i++."</td>";
echo "<td>".$r->roll_no."</td>";
echo "<td>".$r->name."</td>";
echo "<td><a href = '".base_url()."index.php/stud/edit/"
.$r->roll_no."'>Edit</a></td>";
echo "<td><a href = '".base_url()."index.php/stud/delete/"
.$r->roll_no."'>Delete</a></td>";
echo "<tr>";
}
?>
</table>
</body>
</html>
$route['stud'] = "Stud_controller";
$route['stud/add'] = 'Stud_controller/add_student';
$route['stud/add_view'] = 'Stud_controller/add_student_view';
$route['stud/edit/(\d+)'] = 'Stud_controller/update_student_view/$1';
$route['stud/delete/(\d+)'] = 'Stud_controller/delete_student/$1';
http://yoursite.com/index.php/stud
CodeIgniter - Libraries
$this->load->library('class name');
$this->load->library(array('email', 'table'));
Library Classes
Creating Libraries
- Create new library
- Extend the native library
- Replace the native library
Create New Library
- The name of the file must start with a capital letter e.g. Mylibrary.php
- The class name must start with a capital letter e.g. class Mylibrary
- The name of the class and name of the file must match.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mylibrary {
public function some_function() {
}
}
/* End of file Mylibrary.php */
$this->load->library(‘mylibrary’);
$this->mylibrary->some_function();
Extend the Native Library
Class MY_Email extends CI_Email {
}
Replace the Native Library
Class CI_Email {
}
CodeIgniter - Error Handling
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
- show_error() function displays errors in HTML format at the top of the screen.
Syntax | show_error($message, $status_code, $heading = 'An Error Was Encountered') |
Parameters |
|
Return Type | mixed |
- show_404() function displays error if you are trying to access a page which does not exist.
Syntax | show_404($page = '', $log_error = TRUE) |
Parameters |
|
Return Type | void |
- log_message() function is used to write log messages. This is useful when you want to write custom messages.
Syntax | log_message($level, $message, $php_error = FALSE) |
Parameters |
|
Return Type | void |
/*
|--------------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------------
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disable logging, Error logging TURNED OFF
| 1 = Error Message (including PHP errors)
| 2 = Debug Message
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Message, without Error Messages
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
CodeIgniter - File Uploading
Example
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<form action = "" method = "">
<input type = "file" name = "userfile" size = "20" />
<br /><br />
<input type = "submit" value = "upload" />
</form>
</body>
</html>
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<ul>
<?phpforeach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?phpendforeach; ?>
</ul>
<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
</body>
</html>
<?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'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')) {
$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);
}
}
}
?>
$route['upload'] = 'Upload';
http://yoursite.com/index.php/upload
CodeIgniter - Sending Email
- 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
| S.N. | Syntax | Parameters | Return | Return Type |
|---|---|---|---|---|
| 1 | from($from[, $name = ''[, $return_path = NULL]]) | $from (string) − “From” e-mail address $name (string) − “From” display name $return_path (string) − Optional email address to redirect undelivered e-mail to | CI_Email instance (method chaining) | CI_Email |
| 2 | reply_to($replyto[, $name = '']) | $replyto (string) − E-mail address for replies $name (string) − Display name for the reply-to e-mail address | CI_Email instance (method chaining) | CI_Email |
| 2 | to($to) | $to (mixed) − Comma-delimited string or an array of e-mail addresses | CI_Email instance (method chaining) | CI_Email |
| 3 | cc($cc) | $cc (mixed) − Comma-delimited string or an array of e-mail addresses | CI_Email instance (method chaining) | CI_Email |
| 4 | bcc($bcc[, $limit = '']) | $bcc (mixed) − Comma-delimited string or an array of e-mail addresses $limit (int) − Maximum number of e-mails to send per batch | CI_Email instance (method chaining) | CI_Email |
| 5 | subject($subject) | $subject (string) − E-mail subject line | CI_Email instance (method chaining) | CI_Email |
| 6 | message($body) | $body (string) − E-mail message body | CI_Email instance (method chaining) | CI_Email |
| 7 | set_alt_message($str) | $str (string) − Alternative e-mail message body | CI_Email instance (method chaining) | CI_Email |
| 8 | set_header($header, $value) | $header (string) − Header name $value (string) − Header value | CI_Email instance (method chaining) | CI_Email |
| 9 | clear([$clear_attachments = FALSE]) | $clear_attachments(bool) – Whether or not to clear attachments | CI_Email instance (method chaining) | CI_Email |
| 10 | send([$auto_clear = TRUE]) | $auto_clear (bool) − Whether to clear message data automatically | CI_Email instance (method chaining) | CI_Email |
| 11 | attach($filename[, $disposition = ''[, $newname = NULL[, $mime = '']]]) | $filename (string) − File name $disposition (string) − ‘disposition’ of the attachment. Most email clients make their own decision regardless of the MIME specification used here.iana $newname (string) − Custom file name to use in the e-mail $mime (string) − MIME type to use (useful for buffered data) | CI_Email instance (method chaining) | CI_Email |
| 12 | attachment_cid($filename) | $filename (string) − Existing attachment filename | Attachment Content-ID or FALSE if not found | string |
Sending an Email
$this->load->library('email');
$this->email->from('your@example.com', 'Your Name');
$this->email->to('someone@example.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$this->email->send();
Example
<?php
class Email_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
}
public function index() {
$this->load->helper('form');
$this->load->view('email_form');
}
public function send_mail() {
$from_email = "your@example.com";
$to_email = $this->input->post('email');
//Load email library
$this->load->library('email');
$this->email->from($from_email, 'Your Name');
$this->email->to($to_email);
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
//Send mail
if($this->email->send())
$this->session->set_flashdata("email_sent","Email sent successfully.");
else
$this->session->set_flashdata("email_sent","Error in sending Email.");
$this->load->view('email_form');
}
}
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Email Example</title>
</head>
<body>
<?php
echo $this->session->flashdata('email_sent');
echo form_open('/Email_controller/send_mail');
?>
<input type = "email" name = "email" required />
<input type = "submit" value = "SEND MAIL">
<?php
echo form_close();
?>
</body>
</html>
$route['email'] = 'Email_Controller';
http://yoursite.com/index.php/email
CodeIgniter - Form Validation
Example
<html>
<head>
<title>My Form</title>
</head>
<body>
<form action = "" method = "">
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<h5>Name</h5>
<input type = "text" name = "name" value = "" size = "50" />
<div><input type = "submit" value = "Submit" /></div>
</form>
</body>
</html>
<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>
<?php
class Form extends CI_Controller {
public function index() {
/* Load form helper */
$this->load->helper(array('form'));
/* Load form validation library */
$this->load->library('form_validation');
/* Set validation rule for name field in the form */
$this->form_validation->set_rules('name', 'Name', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('myform');
}
else {
$this->load->view('formsuccess');
}
}
}
?>
$route['validation'] = 'Form';
http://yoursite.com/index.php/validation
Validation Rule Reference
CodeIgniter - Session Management
Initializing a Session
$this->load->library('session');
$this->session
Add Session Data
$_SESSION[‘key’] = value;
$this->session->set_userdata('some_name', 'some_value');
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe@some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Remove Session Data
unset($_SESSION[‘some_name’]);
$this->session->unset_userdata('some_name');
$this->session->unset_userdata($array_items);
Fetch Session Data
$name = $this->session->userdata('name');
Example
<?php
class Session_controller extends CI_Controller {
public function index() {
//loading session library
$this->load->library('session');
//adding data to session
$this->session->set_userdata('name','virat');
$this->load->view('session_view');
}
public function unset_session_data() {
//loading session library
$this->load->library('session');
//removing session data
$this->session->unset_userdata('name');
$this->load->view('session_view');
}
}
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Session Example</title>
</head>
<body>
Welcome <?php echo $this->session->userdata('name'); ?>
<br>
<a href = 'http://localhost:85/CodeIgniter-3.0.1/CodeIgniter3.0.1/index.php/sessionex/unset'>
Click Here</a> to unset session data.
</body>
</html>
$route['sessionex'] = 'Session_Controller';
CodeIgniter - Flashdata
Add Flashdata
$this->session->mark_as_flash('item');
- mark_as_flash() function is used for this purpose, which takes only one argument of the value to be stored. We can also pass an array to store multiple values.
- set_flashdata() function can also be used, which takes two arguments, name and value, as shown below. We can also pass an array.
$this->session->set_flashdata('item','value');
Retrieve Flashdata
$this->session->flashdata('item');
Example
<?php
class FlashData_Controller extends CI_Controller {
public function index() {
//Load session library
$this->load->library('session');
//redirect to home page
$this->load->view('flashdata_home');
}
public function add() {
//Load session library
$this->load->library('session');
$this->load->helper('url');
//add flash data
$this->session->set_flashdata('item','item-value');
//redirect to home page
redirect('flashdata');
}
}
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Flashdata Example</title>
</head>
<body>
Flash Data Example
<h2><?php echo $this->session->flashdata('item'); ?></h2>
<a href = 'flashdata/add'>Click Here</a> to add flash data.
</body>
</html>
$route['flashdata'] = 'FlashData_Controller';
$route['flashdata/add'] = 'FlashData_Controller/add';
http://yoursite.com/index.php/flashdata
CodeIgniter - Tempdata
Add Tempdata
// 'item' will be erased after 300 seconds(5 minutes)
$this->session->mark_as_temp('item',300);
$this->session->mark_as_temp(array('item','item2'),300);
// 'item' will be erased after 300 seconds, while 'item2'
// will do so after only 240 seconds
$this->session->mark_as_temp(array(
'item'=>300,
'item2'=>240
));
Retrieve Tempdata
$this->session->tempdata('item');
Remove Tempdata
$this->session->unset_tempdata('item');
Example
<?php
class Tempdata_controller extends CI_Controller {
public function index() {
$this->load->library('session');
$this->load->view('tempdata_view');
}
public function add() {
$this->load->library('session');
$this->load->helper('url');
//tempdata will be removed after 5 seconds
$this->session->set_tempdata('item','item-value',5);
redirect('tempdata');
}
}
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Tempdata Example</title>
</head>
<body>
Temp Data Example
<h2><?php echo $this->session->tempdata('item'); ?></h2>
<a href = 'tempdata/add'>Click Here</a> to add temp data.
</body>
</html>
$route['tempdata'] = "Tempdata_controller";
$route['tempdata/add'] = "Tempdata_controller/add";
http://yoursite.com/index.php/tempdata
Destroying a Session
$this->session->sess_destroy();
CodeIgniter - Cookie Management
Syntax | set_cookie($name[, $value = ''[, $expire = ''[, $domain = ''[, $path = '/'[, $prefix = ''[, $secure = FALSE[, $httponly = FALSE]]]]]]]]) |
Parameters |
|
Return Type | void |
Syntax | get_cookie($index[, $xss_clean = NULL]]) |
Parameters |
|
Return | The cookie value or NULL if not found |
Return Type | mixed |
Syntax | delete_cookie($name[, $domain = ''[, $path = '/'[, $prefix = '']]]]) |
Parameters |
|
Return Type | void |
Example
<?php
class Cookie_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(array('cookie', 'url'));
}
public function index() {
set_cookie('cookie_name','cookie_value','3600');
$this->load->view('Cookie_view');
}
public function display_cookie() {
echo get_cookie('cookie_name');
$this->load->view('Cookie_view');
}
public function deletecookie() {
delete_cookie('cookie_name');
redirect('cookie/display');
}
}
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>
<body>
<a href = 'display'>Click Here</a> to view the cookie.<br>
<a href = 'delete'>Click Here</a> to delete the cookie.
</body>
</html>
$route['cookie'] = "Cookie_controller";
$route['cookie/display'] = "Cookie_controller/display_cookie";
$route['cookie/delete'] = "Cookie_controller/deletecookie";
http://yoursite.com/index.php/cookie
CodeIgniter - Common Functions
| Syntax | is_php($version) |
|---|---|
| Parameters | $version (string) − Version number |
| Return | TRUE if the running PHP version is at least the one specified or FALSE if not |
| Return Type | void |
| Description | Determines if the PHP version being used is greater than the supplied version number. |
| Syntax | is_really_writable($file) |
|---|---|
| Parameters | $file (string) − File path |
| Return | TRUE if the path is writable, FALSE if not |
| Return Type | bool |
| Description | checks to see if file is writable or not. |
| Syntax | config_item($key) |
|---|---|
| Parameters | $key (string) − Config item key |
| Return | Configuration key value or NULL if not found |
| Return Type | mixed |
| Description | This function is used to get the configuration item |
| Syntax | set_status_header($code[, $text = '']) |
|---|---|
| Parameters | $code (int) − HTTP Response status code $text (string) − A custom message to set with the status code |
| Return | |
| Return Type | void |
| Description | This function permits you to manually set a server status header. |
| Syntax | remove_invisible_characters($str[, $url_encoded = TRUE]) |
|---|---|
| Parameters | $str (string) − Input string $url_encoded (bool) − Whether to remove URLencoded characters as well |
| Return | Sanitized string |
| Return Type | string |
| Description | This function prevents inserting NULL characters between ASCII characters |
| Syntax | html_escape($var) |
|---|---|
| Parameters | $var (mixed) − Variable to escape (string or array) |
| Return | HTML escaped string(s) |
| Return Type | mixed |
| Description | This function acts as a native PHP htmlspecialchars() function. |
| Syntax | get_mimes() |
|---|---|
| Return | An associative array of file types |
| Return Type | array |
| Description | This function returns a reference to the MIMEs array from application/config/mimes.php. |
| Syntax | is_https() |
|---|---|
| Return | TRUE if currently using HTTP-over-SSL, FALSE if not |
| Return Type | bool |
| Description | Returns TRUE if a secure (HTTPS) connection is used and FALSE in any other case (including non-HTTP requests). |
| Syntax | is_cli() |
|---|---|
| Return | TRUE if currently running under CLI, FALSE otherwise |
| Return Type | bool |
| Description | Returns TRUE if the application is run through the command line and FALSE if not. |
| Syntax | function_usable($function_name) |
|---|---|
| Parameters | $function_name (string) − Function name |
| Return Type | bool |
| Description | Returns TRUE if a function exists and is usable, FALSE otherwise. |
Example
<?php
class CommonFun_Controller extends CI_Controller {
public function index() {
set_status_header(200);
echo is_php('5.3')."<br>";
var_dump(is_really_writable('./Form.php'));
echo config_item('language')."<br>";
echo remove_invisible_characters('This is a test','UTF8')."<br>";
$str = '< This > is \' a " test & string';
echo html_escape($str)."<br>";
echo "is_https():".var_dump(is_https())."<br>";
echo "is_cli():".var_dump(is_cli())."<br>";
var_dump(function_usable('test'))."<br>";
echo "get_mimes():".print_r(get_mimes())."<br>";
}
public function test() {
echo "Test function";
}
}
?>
$route['commonfunctions'] = 'CommonFun_Controller';
http://yoursite.com/index.php/commonfunctions
CodeIgniter - Page Caching
Enable Caching
$this->output->cache($n);
Disable Caching
// Deletes cache for the currently requested URI
$this->output->delete_cache();
// Deletes cache for /foo/bar
$this->output->delete_cache('/foo/bar');
Example
<?php
class Cache_controller extends CI_Controller {
public function index() {
$this->output->cache(1);
$this->load->view('test');
}
public function delete_file_cache() {
$this->output->delete_cache('cachecontroller');
}
}
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>
<body>
CodeIgniter View Example
</body>
</html>
$route['cachecontroller'] = 'Cache_controller';
$route['cachecontroller/delete'] = 'Cache_controller/delete_file_cache';
http://yoursite.com/index.php/cachecontroller
http://yoursite.com/index.php/cachecontroller/delete
CodeIgniter - Page Redirection
Syntax | redirect($uri = '', $method = 'auto', $code = NULL) |
Parameters |
|
Return type | void |
Example
<?php
class Redirect_controller extends CI_Controller {
public function index() {
/*Load the URL helper*/
$this->load->helper('url');
/*Redirect the user to some site*/
redirect('http://www.tutorialspoint.com');
}
public function computer_graphics() {
/*Load the URL helper*/
$this->load->helper('url');
redirect('http://www.tutorialspoint.com/computer_graphics/index.htm');
}
public function version2() {
/*Load the URL helper*/
$this->load->helper('url');
/*Redirect the user to some internal controller’s method*/
redirect('redirect/computer_graphics');
}
}
?>
$route['redirect'] = 'Redirect_controller';
$route['redirect/version2'] = 'Redirect_controller/version2';
$route['redirect/computer_graphics'] = 'Redirect_controller/computer_graphics';
http://yoursite.com/index.php/redirect
http://yoursite.com/index.php/redirect/computer_graphics
CodeIgniter - Application Profiling
Enable Profiling
$this->output->enable_profiler(TRUE);
Disable Profiling
$this->output->enable_profiler(FALSE);
Enable / Disable Profiler Section
$config['queries'] = TRUE;
| Key | Description | Default |
|---|---|---|
benchmarks | Elapsed time of Benchmark points and total execution time | TRUE |
config | CodeIgniterConfig variables | TRUE |
controller_info | The Controller class and method requested | TRUE |
get | Any GET data passed in the request | TRUE |
http_headers | The HTTP headers for the current request | TRUE |
memory_usage | Amount of memory consumed by the current request, in bytes | TRUE |
post | Any POST data passed in the request | TRUE |
queries | Listing of all database queries executed, including execution time | TRUE |
uri_string | The URI of the current request | TRUE |
session_data | Data stored in the current session | TRUE |
query_toggle_count | The number of queries after which the query block will default to hidden. | 25 |
$sections = array(
'config' => TRUE,
'queries' => TRUE
);
$this->output->set_profiler_sections($sections);
CodeIgniter - Benchmarking
Setting Benchmark Points
<?php
$this->benchmark->mark('code_start');
// Some code happens here
$this->benchmark->mark('code_end');
echo $this->benchmark->elapsed_time('code_start', 'code_end');
?>
<?php
echo $this->benchmark->memory_usage();
?>
Example
<?php
class Profiler_controller extends CI_Controller {
public function index() {
//enable profiler
$this->output->enable_profiler(TRUE);
$this->load->view('test');
}
public function disable() {
//disable profiler
$this->output->enable_profiler(FALSE);
$this->load->view('test');
}
}
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
</head>
<body>
CodeIgniter View Example
</body>
</html>
$route['profiler'] = "Profiler_controller";
$route['profiler/disable'] = "Profiler_controller/disable"
http://yoursite.com/index.php/profiler
http://yoursite.com/index.php/profiler/disable
CodeIgniter - Adding JS & CSS
For example, let us assume, you have created one JavaScript file sample.jsand one CSS file style.css. Now, to add these files into your views, load URL helper in your controller as shown below.
$this->load->helper('url');
<link rel = "stylesheet" type = "text/css"
href = "<?php echo base_url(); ?>css/style.css">
<script type = 'text/javascript' src = "<?php echo base_url();
?>js/sample.js"></script>
Example
<?php
class Test extends CI_Controller {
public function index() {
$this->load->helper('url');
$this->load->view('test');
}
}
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter View Example</title>
<link rel = "stylesheet" type = "text/css"
href = "<?php echo base_url(); ?>css/style.css">
<script type = 'text/javascript' src = "<?php echo base_url();
?>js/sample.js"></script>
</head>
<body>
<a href = 'javascript:test()'>Click Here</a> to execute the javascript function.
</body>
</html>
body {
background:#000;
color:#FFF;
}
function test() {
alert('test');
}
$route['profiler'] = "Profiler_controller";
$route['profiler/disable'] = "Profiler_controller/disable"
http://yoursite.com/index.php/test
CodeIgniter - Internationalization
Creating files Language
$lang[‘key’] = ‘val’;
Loading Language file
$this->lang->load('filename', 'language');
- filename − It is the name of file you want to load. Don’t use extension of file here but only name of file.
- Language − It is the language set containing it.
Fetching Language Text
$this->lang->line('language_key');
Autoload Languages
| -----------------------------------------------------------------------
| Auto-load Language files
| -----------------------------------------------------------------------
| Prototype:
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
Example
<?php
class Lang_controller extends CI_Controller {
public function index(){
//Load form helper
$this->load->helper('form');
//Get the selected language
$language = $this->input->post('language');
//Choose language file according to selected lanaguage
if($language == "french")
$this->lang->load('french_lang','french');
else if($language == "german")
$this->lang->load('german_lang','german');
else
$this->lang->load('english_lang','english');
//Fetch the message from language file.
$data['msg'] = $this->lang->line('msg');
$data['language'] = $language;
//Load the view file
$this->load->view('lang_view',$data);
}
}
?>
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>CodeIgniter Internationalization Example</title>
</head>
<body>
<?php
echo form_open('/lang');
?>
<select name = "language" onchange = "javascript:this.form.submit();">
<?php
$lang = array('english'=>"English",'french'=>"French",'german'=>"German");
foreach($lang as $key=>$val) {
if($key == $language)
echo "<option value = '".$key."' selected>".$val."</option>";
else
echo "<option value = '".$key."'>".$val."</option>";
}
?>
</select>
<br>
<?php
form_close();
echo $msg;
?>
</body>
</html>
<?php
$lang['msg'] = "CodeIgniter Internationalization example.";
?>
<?php
$lang['msg'] = "Exemple CodeIgniter internationalisation.";
?>
<?php
$lang['msg'] = "CodeIgniter Internationalisierung Beispiel.";
?>
$route['lang'] = "Lang_controller";
http://yoursite.com/index.php/lang
CodeIgniter - Security
XSS Prevention
$data = $this->security->xss_clean($data);
SQL Injection Prevention
- Escaping Queries
- Query Biding
- Active Record Class
Escaping Queries
<?php
$username = $this->input->post('username');
$query = 'SELECT * FROM subscribers_tbl WHERE user_name = '.
$this->db->escape($email);
$this->db->query($query);
?>
Query Biding
<?php
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
?>
Active Record Class
<?php
$this->db->get_where('subscribers_tbl',array
('status'=> active','email' => 'info@arjun.net.in'));
?>
Hiding PHP Errors
PHP Error Reporting Level
Database Error
$db['default']['db_debug'] = FALSE;
Error log
$config['log_threshold'] = 1;
CSRF Prevention
$config['csrf_protection'] = TRUE;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array('api/person/add');
Password Handling
- DO NOT store passwords in plain-text format.
- Always hash your passwords.
- DO NOT use Base64 or similar encoding for storing passwords.
- DO NOT use weak or broken hashing algorithms like MD5 or SHA1. Only use strong password hashing algorithms like BCrypt, which is used in PHP’s own Password Hashing functions.
- DO NOT ever display or send a password in plain-text format.
- DO NOT put unnecessary limits on your users’ passwords.





















