Introduction to CodeIgniter
CodeIgniter is a lightweight, open-source PHP framework built for developers who need a simple, elegant toolkit to create full-featured web applications. Known for its small footprint, exceptional performance, and minimal configuration requirements, CodeIgniter follows an MVC (Model-View-Controller) architectural pattern. It provides a rich set of libraries for common tasks while maintaining flexibility, allowing developers to focus on building applications rather than framework intricacies.
Core Concepts
MVC Architecture in CodeIgniter
- Model: Handles data and business logic
- View: Presents data to users (UI/UX)
- Controller: Processes requests, interacts with models, and loads views
Directory Structure
application/
├── config/ # Configuration files
├── controllers/ # Controller classes
├── core/ # Core system extensions
├── helpers/ # Helper functions
├── hooks/ # Hook classes
├── language/ # Language files
├── libraries/ # Custom libraries
├── models/ # Model classes
├── third_party/ # Third-party packages
└── views/ # View files
system/ # CodeIgniter core files
public/ # Web-accessible files
├── index.php # Front controller
├── assets/ # CSS, JS, images
└── .htaccess # URL rewriting rules
Installation and Configuration
Installation Methods
Manual Installation:
- Download from codeigniter.com
- Extract files to web server directory
- Configure application/config/config.php
Composer Installation (CI4):
composer create-project codeigniter4/appstarter project-name
Essential Configuration Files
File | Purpose | Key Settings |
---|---|---|
config.php | Core configuration | Base URL, encryption key, session settings |
database.php | Database connections | DB credentials, connection settings |
routes.php | URL routing rules | Default controller, custom routes |
autoload.php | Auto-loaded resources | Models, libraries, helpers to load automatically |
Environment Setup (CI4)
// .env file
CI_ENVIRONMENT = development # or production
app.baseURL = 'http://localhost:8080/'
database.default.hostname = localhost
database.default.database = ci4_database
database.default.username = root
database.default.password = password
Controllers
Basic Controller
<?php
// application/controllers/Blog.php
class Blog extends CI_Controller {
public function index() {
$this->load->view('blog_view');
}
public function post($id) {
$data['post_id'] = $id;
$this->load->view('post_view', $data);
}
}
Loading Resources
$this->load->model('blog_model'); // Load model
$this->load->library('session'); // Load library
$this->load->helper('url'); // Load helper
$this->load->database(); // Load database
$this->load->view('view_name', $data); // Load view with data
Returning Different Response Types
// JSON Response
public function get_data() {
$data = $this->some_model->get_data();
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
// XML Response
public function get_xml() {
$this->load->helper('xml');
$xml = array_to_xml($data, '<root/>');
$this->output
->set_content_type('text/xml')
->set_output($xml->asXML());
}
Models
Basic Model
<?php
// application/models/Blog_model.php
class Blog_model extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->database();
}
public function get_posts($limit = 10, $offset = 0) {
$query = $this->db->get('posts', $limit, $offset);
return $query->result();
}
public function get_post($id) {
$query = $this->db->get_where('posts', ['id' => $id]);
return $query->row();
}
}
Database Operations
Query Builder
// SELECT
$query = $this->db->get('table_name'); // SELECT * FROM table_name
$query = $this->db->get_where('table', ['id' => 1]); // SELECT * FROM table WHERE id = 1
// Customizing Queries
$this->db->select('title, content, date');
$this->db->from('posts');
$this->db->where('status', 'published');
$this->db->order_by('date', 'DESC');
$this->db->limit(10);
$query = $this->db->get();
// INSERT
$data = [
'title' => 'New Post',
'content' => 'Post content',
'author_id' => 1
];
$this->db->insert('posts', $data);
$insert_id = $this->db->insert_id();
// UPDATE
$data = ['title' => 'Updated Title'];
$this->db->where('id', 5);
$this->db->update('posts', $data);
// DELETE
$this->db->delete('posts', ['id' => 5]);
// JOIN
$this->db->select('posts.*, categories.name as category');
$this->db->from('posts');
$this->db->join('categories', 'categories.id = posts.category_id');
$query = $this->db->get();
// Raw Queries
$query = $this->db->query("SELECT * FROM posts WHERE author_id = ?", [3]);
Transactions
$this->db->trans_begin();
$this->db->query('INSERT INTO users (username) VALUES ("user1")');
$this->db->query('INSERT INTO profiles (user_id) VALUES (?)', [$user_id]);
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
Views
Basic View
<!-- application/views/blog_view.php -->
<!DOCTYPE html>
<html>
<head>
<title><?= $title ?? 'My Blog' ?></title>
</head>
<body>
<h1><?= $heading ?? 'Welcome to My Blog' ?></h1>
<div class="content">
<?php foreach ($posts as $post): ?>
<article>
<h2><?= $post->title ?></h2>
<p><?= $post->excerpt ?></p>
</article>
<?php endforeach; ?>
</div>
</body>
</html>
View Partials
// Loading a partial view
$this->load->view('header', $header_data);
$this->load->view('content', $content_data);
$this->load->view('footer', $footer_data);
// Returning view as string instead of outputting
$string = $this->load->view('view_name', $data, TRUE);
Routing
Basic Routes
// application/config/routes.php
$route['default_controller'] = 'home';
$route['404_override'] = 'errors/page_404';
$route['translate_uri_dashes'] = FALSE;
// Static routes
$route['about'] = 'pages/about';
$route['contact'] = 'pages/contact';
// Dynamic routes with parameters
$route['blog/(:num)'] = 'blog/post/$1';
$route['products/(:any)'] = 'catalog/product_details/$1';
// RESTful routes (CI4)
$route->resource('api/users'); // Creates all REST endpoints for users
Route Groups (CI4)
$routes->group('admin', function($routes) {
$routes->add('users', 'Admin\Users::index');
$routes->add('products', 'Admin\Products::index');
});
// Creates: /admin/users and /admin/products
Form Handling
Form Creation
<?= form_open('controller/method', ['class' => 'form']); ?>
<div>
<?= form_label('Username:', 'username'); ?>
<?= form_input(['name' => 'username', 'id' => 'username', 'value' => set_value('username')]); ?>
<?= form_error('username'); ?>
</div>
<div>
<?= form_label('Email:', 'email'); ?>
<?= form_input(['name' => 'email', 'id' => 'email', 'type' => 'email', 'value' => set_value('email')]); ?>
<?= form_error('email'); ?>
</div>
<div>
<?= form_submit('submit', 'Submit', ['class' => 'btn']); ?>
</div>
<?= form_close(); ?>
Form Validation
// Controller
public function register() {
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|is_unique[users.username]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[8]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required|matches[password]');
if ($this->form_validation->run() == FALSE) {
$this->load->view('register_form');
} else {
$this->user_model->register_user();
$this->load->view('register_success');
}
}
Sessions
Session Management
// Initialize
$this->load->library('session');
// Set session data
$this->session->set_userdata('name', 'John Doe');
$this->session->set_userdata(['email' => 'john@example.com', 'logged_in' => TRUE]);
// Get session data
$name = $this->session->userdata('name');
$all_data = $this->session->userdata();
// Check if session data exists
if ($this->session->has_userdata('logged_in')) {
// User is logged in
}
// Remove session data
$this->session->unset_userdata('name');
$this->session->unset_userdata(['email', 'logged_in']);
// Set flash data (available for the next request only)
$this->session->set_flashdata('message', 'Registration successful!');
// Get flash data
$message = $this->session->flashdata('message');
// Destroy session
$this->session->sess_destroy();
Helper Functions
URL Helper
// Load the helper
$this->load->helper('url');
// Generate links
echo base_url(); // http://example.com/
echo site_url('blog/post/123'); // http://example.com/index.php/blog/post/123
echo anchor('blog/post/123', 'Read More'); // <a href="http://example.com/index.php/blog/post/123">Read More</a>
// Redirects
redirect('controller/method'); // Redirects browser
Form Helper
$this->load->helper('form');
echo form_open('email/send'); // <form action="http://example.com/index.php/email/send" method="post">
echo form_input('username', 'johndoe'); // <input type="text" name="username" value="johndoe" />
echo form_password('password', ''); // <input type="password" name="password" value="" />
echo form_submit('submit', 'Submit'); // <input type="submit" name="submit" value="Submit" />
echo form_close(); // </form>
Array Helper
$this->load->helper('array');
$person = ['name' => 'John', 'email' => 'john@example.com', 'status' => 'active'];
$name = element('name', $person, 'Unknown'); // Returns 'John' or 'Unknown' if not found
Text Helper
$this->load->helper('text');
$string = 'This is a long paragraph that needs to be truncated...';
echo character_limiter($string, 20); // This is a long...
echo word_limiter($string, 4); // This is a long...
echo word_censor($string, ['long']); // This is a **** paragraph...
Common Libraries
Email Library
$this->load->library('email');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'smtp.example.com';
$config['smtp_user'] = 'email@example.com';
$config['smtp_pass'] = 'password';
$config['smtp_port'] = 465;
$config['smtp_crypto'] = 'ssl';
$config['mailtype'] = 'html';
$this->email->initialize($config);
$this->email->from('sender@example.com', 'Sender Name');
$this->email->to('recipient@example.com');
$this->email->cc('cc@example.com');
$this->email->bcc('bcc@example.com');
$this->email->subject('Email Subject');
$this->email->message('Email body content');
$this->email->attach('/path/to/file.pdf');
if ($this->email->send()) {
echo 'Email sent successfully';
} else {
echo $this->email->print_debugger();
}
Upload Library
$this->load->library('upload');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|pdf';
$config['max_size'] = 2048; // KB
$config['encrypt_name'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile')) {
$error = $this->upload->display_errors();
// Handle error
} else {
$data = $this->upload->data();
// File uploaded successfully
// $data['file_name'] contains the new filename
}
Image Manipulation Library
$this->load->library('image_lib');
// Resize image
$config['image_library'] = 'gd2';
$config['source_image'] = './uploads/original.jpg';
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 800;
$config['height'] = 600;
$this->image_lib->initialize($config);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
// Crop image
$this->image_lib->clear();
$config['image_library'] = 'gd2';
$config['source_image'] = './uploads/original.jpg';
$config['width'] = 300;
$config['height'] = 300;
$config['x_axis'] = 100;
$config['y_axis'] = 100;
$this->image_lib->initialize($config);
if (!$this->image_lib->crop()) {
echo $this->image_lib->display_errors();
}
Pagination Library
$this->load->library('pagination');
$config['base_url'] = site_url('blog/index');
$config['total_rows'] = $this->blog_model->count_all();
$config['per_page'] = 10;
$config['uri_segment'] = 3;
$config['full_tag_open'] = '<ul class="pagination">';
$config['full_tag_close'] = '</ul>';
$config['first_link'] = 'First';
$config['last_link'] = 'Last';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['prev_link'] = '«';
$config['prev_tag_open'] = '<li class="prev">';
$config['prev_tag_close'] = '</li>';
$config['next_link'] = '»';
$config['next_tag_open'] = '<li>';
$config['next_tag_close'] = '</li>';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li class="active"><a href="#">';
$config['cur_tag_close'] = '</a></li>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['results'] = $this->blog_model->get_posts($config['per_page'], $page);
$data['links'] = $this->pagination->create_links();
$this->load->view('blog_view', $data);
Security Features
Cross-Site Request Forgery (CSRF) Protection
// Enable CSRF protection in config/config.php
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_token';
$config['csrf_cookie_name'] = 'csrf_cookie';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
// In your view form
<?= form_open('controller/method'); ?>
<!-- CSRF token is automatically included -->
XSS Filtering
// In config/config.php
$config['global_xss_filtering'] = TRUE; // Global XSS filtering
// Manual filtering
$clean_data = $this->security->xss_clean($input_data);
SQL Injection Prevention
// Query binding (preferred method)
$this->db->query("SELECT * FROM users WHERE username = ?", [$username]);
// Using Query Builder (auto-escaped)
$this->db->get_where('users', ['username' => $username]);
Custom Libraries
Creating a Custom Library
<?php
// application/libraries/Pdf.php
class Pdf {
public function __construct() {
// Constructor code
log_message('debug', 'PDF Library Initialized');
}
public function generate($html, $filename) {
// Library methods
}
}
// Using the library
$this->load->library('pdf');
$this->pdf->generate($html, 'document.pdf');
Extending Native Libraries
<?php
// application/libraries/MY_Email.php
class MY_Email extends CI_Email {
public function __construct() {
parent::__construct();
}
public function quick_send($to, $subject, $message) {
$this->from('system@example.com', 'System');
$this->to($to);
$this->subject($subject);
$this->message($message);
return $this->send();
}
}
// Using the extended library
$this->load->library('email');
$this->email->quick_send('user@example.com', 'Test', 'Test message');
Hooks
Hook Points and Configuration
// application/config/hooks.php
$hook['pre_system'] = [
'class' => 'MyHook',
'function' => 'pre_system_method',
'filename' => 'MyHook.php',
'filepath' => 'hooks'
];
$hook['post_controller_constructor'] = [
'class' => 'Auth',
'function' => 'check_access',
'filename' => 'Auth.php',
'filepath' => 'hooks'
];
// Enable hooks in config/config.php
$config['enable_hooks'] = TRUE;
Hook Class Example
<?php
// application/hooks/MyHook.php
class MyHook {
public function pre_system_method() {
// Execute before the system execution
}
}
Common Challenges & Solutions
Problem: “404 Page Not Found” Errors
- Check if the controller class name starts with uppercase letter
- Verify that the file name matches the class name exactly
- Make sure .htaccess is properly configured for URL rewriting
- Check if routes are properly defined in routes.php
Problem: Database Connection Issues
- Double-check database credentials in database.php
- Verify that database server is running
- Check for proper database driver installation
- Try connecting with a standalone PHP script to isolate the issue
Problem: Session Data Not Persisting
- Check session configuration in config.php
- Verify session storage directory is writable
- Make sure session cookies are not being blocked
- Check for session timeout settings
Problem: File Upload Errors
- Verify upload directory permissions (chmod 777 for testing)
- Check php.ini settings for upload_max_filesize and post_max_size
- Ensure proper enctype=”multipart/form-data” in form tag
- Check for file type restrictions in upload configuration
Best Practices
- Follow CodeIgniter’s style guide (found in user guide)
- Use Query Builder instead of raw SQL when possible
- Implement proper input validation for all user inputs
- Organize business logic in models, not controllers
- Use libraries for reusable code across multiple controllers
- Leverage helpers for simple utility functions
- Implement proper error handling and logging
- Use environment-specific configuration files
- Create base controllers for common functionality
- Document your code thoroughly with PHPDoc comments
CodeIgniter 4 Specific Features
Namespaces
namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\Controller;
class Users extends Controller {
public function index() {
$model = new UserModel();
$data['users'] = $model->findAll();
return view('users/index', $data);
}
}
Entity Classes
namespace App\Entities;
use CodeIgniter\Entity\Entity;
class User extends Entity {
protected $casts = [
'id' => 'integer',
'active' => 'boolean',
'created_at' => 'datetime',
];
public function setPassword(string $password) {
$this->attributes['password'] = password_hash($password, PASSWORD_BCRYPT);
return $this;
}
public function verifyPassword(string $password) {
return password_verify($password, $this->attributes['password']);
}
}
Filters (Middleware)
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
class Auth implements FilterInterface {
public function before(RequestInterface $request, $arguments = null) {
if (!session()->get('logged_in')) {
return redirect()->to('/login');
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {
// Do something after the controller execution
}
}
// app/Config/Filters.php
public $filters = [
'auth' => [
'before' => [
'admin/*',
'dashboard',
]
]
];
Command-Line Interface
# Create a new controller
php spark make:controller Blog
# Create a new model
php spark make:model UserModel
# Create a migration
php spark make:migration create_users_table
# Run migrations
php spark migrate
# Rollback migration
php spark migrate:rollback
# Seed the database
php spark db:seed UserSeeder
# Show routes
php spark routes
# Run the development server
php spark serve
Resources for Further Learning
Official Documentation
Community Resources
Recommended Books
- “Pro PHP and jQuery with CodeIgniter” by Brad Dayley
- “CodeIgniter Web Application Blueprints” by Rob Foster
- “Learning CodeIgniter” by Sk Arshad
Video Tutorials
- Codecourse – CodeIgniter Tutorial Series
- YouTube channel: “ion_auth”
- Udemy: “Learn CodeIgniter 4 From Scratch”
This cheat sheet covers the essential aspects of CodeIgniter for both versions 3 and 4, with specific CI4 features highlighted separately. It should serve as a comprehensive reference for both beginners and intermediate developers working with this framework.