CodeIgniter Tutorial for Beginners & Professionals: Learn MVC, Routing, CRUD & More

Updated on 21/07/20251,981 Views

Ever wondered how top developers build lightning-fast web apps without spending weeks writing boilerplate code? If you’ve dabbled in PHP and felt overwhelmed by heavy frameworks, there’s good news—CodeIgniter is here to simplify things.

Lightweight, powerful, and remarkably beginner-friendly, CodeIgniter is one of the most trusted PHP frameworks used for building dynamic web applications. Whether you're a student trying to build your first project or a professional aiming to create scalable backends, CodeIgniter offers a clean, logical structure that doesn’t get in your way.

In this step-by-step CodeIgniter tutorial, we’ll cover everything from setting up the framework to building APIs, working with databases, and deploying real-world projects. No jargon, no fluff—just practical knowledge to help you get your hands dirty with confidence.

So if you're ready to build faster, code cleaner, and learn smarter, let's get started.

If you are looking to upgrade your software engineering skills, you can choose the top software engineering courses offered by upGrad and level up your career.

What is CodeIgniter?

CodeIgniter is an open-source PHP framework designed to help developers build dynamic websites and web applications quickly. It follows the Model-View-Controller (MVC) architecture, which separates business logic from presentation, making code easier to manage and scale. Known for its speed, lightweight structure, and minimal configuration, CodeIgniter allows both beginners and experienced developers to build robust PHP applications with clean and reusable code.

Top Software Engineering Courses offered by upGrad

Why Use CodeIgniter?

If you're looking for a fast, flexible, and beginner-friendly framework, CodeIgniter stands out for several reasons:

  • Lightweight Performance: With a small footprint, it runs faster than many PHP frameworks.
  • Easy to Learn: Its intuitive syntax and detailed documentation make it ideal for beginners.
  • Minimal Setup: You can start coding right away, no need for complex configurations.
  • Built-in Tools: From form validation to session handling, it offers essential tools out of the box.
  • Excellent Compatibility: Works smoothly with shared hosting environments and most PHP servers.

Key Features of CodeIgniter Framework

Here are some of the standout features that make CodeIgniter a popular choice among PHP developers:

  • MVC Architecture: Clean separation of concerns for better organization and scalability.
  • Built-in Security: Protection against CSRF, XSS, and SQL injection.
  • Form Validation: Powerful and customizable validation rules.
  • Error Handling & Debugging: Easy-to-understand error messages and logs.
  • Session Management: Secure session control with database or file-based options.
  • Caching System: Speeds up your application with page, data, or query caching.
  • Extensibility: Supports third-party libraries, plugins, and custom helpers.

How to Set Up CodeIgniter?

Before jumping into coding, it’s important to properly install and configure CodeIgniter. Whether you're a college student setting up your first PHP project or a developer deploying a new app, this section walks you through the setup smoothly.

Prerequisites for CodeIgniter Installation

Server Requirements

To run CodeIgniter smoothly, make sure your system meets these basic requirements:

  • PHP Version:
    • CodeIgniter 3: PHP 5.6 or newer
    • CodeIgniter 4: PHP 7.4 or newer (preferably PHP 8+ for better performance and security)
  • Web Server:

Apache with mod_rewrite enabled or Nginx

  • Database Support:

MySQL (5.1+), PostgreSQL, or SQLite depending on your project needs

Tools Needed (XAMPP, Composer, etc.)

Here are some essential tools to install before setting up CodeIgniter:

  • XAMPP / MAMP / WAMP: All-in-one local servers with Apache, PHP, and MySQL
  • Composer (mandatory for CodeIgniter 4): Dependency manager for PHP
  • Code Editor: VS Code, Sublime Text, or PHPStorm for a better coding experience
  • Browser: Chrome or Firefox with developer tools

Installing CodeIgniter (CI 3 and CI 4)

CodeIgniter 3 Installation (Manual)

  • Download CI 3 zip from CodeIgniter Website
  • Extract and move it to your htdocs (XAMPP) or www (WAMP) folder
  • Rename the folder to your project name
  • Open in browser using: http://localhost/your_project_name

CodeIgniter 4 Installation (Composer Recommended)

composer create-project codeigniter4/appstarter your_project_name

Or download the zip from the CI 4 Download Page and follow similar steps as CI 3.

Folder Structure Overview

Understanding the folder layout is key for efficient development:

CodeIgniter 4 Main Folders:

  • /app – Your application code (Controllers, Models, Views, Config)
  • /public – Entry point (index.php) for web access
  • /system – Core CodeIgniter framework files (avoid modifying)
  • /writable – Logs, cache, and uploads
  • /tests – Unit and feature tests
  • /vendor – Composer dependencies (CI 4)

Configuration Basics

Before you begin development, there are a few basic configurations you should do.

Configuring Base URL

This defines your website’s root path. Set it in:

// CI 4: app/Config/App.php
public string $baseURL = 'http://localhost/your_project/';

Make sure it ends with a trailing slash and matches your local or production domain.

Enabling Error Reporting

During development, error reporting helps you debug easily.

  • In CI 3, set:
error_reporting(E_ALL);
ini_set('display_errors', 1);
  • In CI 4, update the .env file:
CI_ENVIRONMENT = development

This activates the debug toolbar and shows detailed error messages.

Autoloading Libraries and Helpers

Instead of loading components in every file, CodeIgniter allows autoloading:

  • In CI 3:

Edit application/config/autoload.php

$autoload['libraries'] = ['session', 'database'];
$autoload['helper'] = ['url', 'form'];
  • In CI 4:

Edit app/Config/Autoload.php and register services or use Composer's PSR-4 autoloading.

Core Concepts of CodeIgniter

Understanding CodeIgniter’s core building blocks is essential before jumping into coding. From its elegant MVC architecture to handling forms, URLs, and sessions, this section gives you a strong foundation to build scalable and maintainable PHP applications.

MVC Architecture in CodeIgniter

CodeIgniter is based on the MVC (Model-View-Controller) pattern. It separates your application logic into three core components:

  • Model: Handles all database interactions and business logic.
  • View: Manages the layout and display of your web pages (HTML, CSS, etc.).
  • Controller: Acts as the brain, it receives user requests, processes them via Models, and returns results via Views.

Routing in CodeIgniter

Routing determines how URLs map to controllers and methods.

In CodeIgniter 4, routes are defined in /app/Config/Routes.php:

$routes->get('/about', 'Pages::about');

This line tells CI to load the about method from the Pages controller when someone visits yourdomain.com/about.

You can also use:

  • Route groups for APIs
  • Filters for authentication
  • Dynamic segments like (:num) or (:any)

Controllers, Views, and Models

Creating Your First Controller

Controllers live inside /app/Controllers.

Example: Home.php

namespace App\Controllers;

class Home extends BaseController {
    public function index() {
        return view('welcome_message');
    }
}

Visit http://localhost/your_project/public/ to see your controller in action.

Loading Views and Passing Data

Create a view file inside /app/Views/welcome_message.php.

To pass data from controller to view:

$data = ['title' => 'Welcome to CodeIgniter'];
return view('welcome_message', $data);

In your view:

<h1><?= esc($title); ?></h1>

Building Simple Models

Models reside in /app/Models.

Example:

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model {
    protected $table = 'users';
    protected $allowedFields = ['name', 'email'];
}

To use it:

$userModel = new \App\Models\UserModel();
$users = $userModel->findAll();

Libraries, Helpers, and Plugins

CodeIgniter offers a variety of built-in libraries (classes), helpers (function sets), and support for third-party plugins.

  • Libraries: session, email, pagination, etc.
  • Helpers: url_helper, form_helper, text_helper

To load:

helper('url'); // loads url helper
$this->session = \Config\Services::session(); // in CI 4

URL and URI Segments

CodeIgniter provides clean and SEO-friendly URLs. You can access specific segments of a URL like this:

$segment = $this->request->uri->getSegment(2); // Gets 2nd part of URL

Example:

URL: example.com/blog/view/10

  • Segment(1) = blog
  • Segment(2) = view
  • Segment(3) = 10

This is useful for passing dynamic values like IDs, slugs, or page names.

Working with Forms and Input Class

CodeIgniter simplifies form handling through its built-in Input and Form Validation libraries.

Form Example:

<form method="post" action="/submit">
<input type="text" name="email" />
<button type="submit">Submit</button>
</form>

Getting Input in Controller:

$email = $this->request->getPost('email');

Validating Input:

$validation = \Config\Services::validation();
$validation->setRules(['email' => 'required|valid_email']);
if (!$validation->withRequest($this->request)->run()) {
echo $validation->listErrors();
}

Session and Cookies Handling

Sessions and cookies are key to managing user login, cart data, or any temporary state.

Starting a session:

$session = session();
$session->set('username', 'John');

Retrieving session data:

echo $session->get('username');

Setting cookies:

setcookie('user_id', '123', time() + 3600);

Reading cookies:

echo $_COOKIE['user_id'];

In CI 4, sessions are highly secure and can be configured to use files, databases, or Redis.

Database Handling in CodeIgniter

CodeIgniter makes database operations simple and efficient through its intuitive APIs and Query Builder class. Whether you’re creating a blog, inventory system, or login module, mastering database interactions is a must.

Let’s walk through the essentials—from configuration to CRUD operations—all tailored for students and professionals looking to build real-world PHP apps.

Database Configuration

Before interacting with your database, you need to configure it in CodeIgniter.

For CodeIgniter 4, the configuration is located in:

/app/Config/Database.php

Here’s a basic setup for a MySQL database:

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'your_database',
    'DBDriver' => 'MySQLi',
];

Once configured, CodeIgniter handles all connections internally, and you can start querying without writing raw SQL.

CRUD Operations in CodeIgniter

CRUD stands for Create, Read, Update, and Delete—the foundational actions in any database-driven app. CodeIgniter’s Model and Query Builder make it easy to perform these with minimal code.

Inserting Data

Example using a model:

$data = [
    'name' => 'John Doe',
    'email' => '[email protected]'
];

$userModel = new \App\Models\UserModel();
$userModel->insert($data);

This inserts a new row into the users table.

Reading Data

To retrieve all users:

$users = $userModel->findAll();

To fetch a specific user by ID:

$user = $userModel->find(5);

You can also use custom conditions:

$user = $userModel->where('email', '[email protected]')->first();

Updating Records

To update a user:

$data = ['name' => 'Jane Doe'];
$userModel->update(5, $data);

This will update the name where the ID is 5.

Deleting Records

To delete a user:

$userModel->delete(5);

You can also delete with conditions:

$userModel->where('email', '[email protected]')->delete();

Query Builder Class

CodeIgniter's Query Builder lets you construct SQL queries using PHP methods, making your code more readable and secure.

Example:

$db = \Config\Database::connect();
$builder = $db->table('users');

$builder->select('name, email');
$builder->where('status', 'active');
$query = $builder->get();

$results = $query->getResult();

You can use it for:

  • select(), insert(), update(), delete()
  • Joins, grouping, ordering
  • Limits and pagination

Active Record Pattern

The Active Record pattern is a design approach where each database table is represented by a class. CodeIgniter models follow this approach.

Instead of writing raw SQL:

SELECT * FROM users WHERE email = '[email protected]';

You write:

$user = $userModel->where('email', '[email protected]')->first();

Benefits:

  • Cleaner, chainable syntax
  • Reusable queries
  • Improved security
  • Easier testing and debugging

Form Validation and Error Handling

CodeIgniter includes a powerful Form Validation library that helps validate and sanitize user inputs before interacting with the database.

Example:

$validation = \Config\Services::validation();

$validation->setRules([
    'name' => 'required|min_length[3]',
    'email' => 'required|valid_email'
]);

if (!$validation->withRequest($this->request)->run()) {
    return redirect()->back()->withInput()->with('errors', $validation->getErrors());
}

If validation fails, it redirects back with errors. This is a best practice to prevent malformed or malicious data from entering your database.

Conclusion

CodeIgniter is a popular framework for PHP developers seeking speed, simplicity, and flexibility. By understanding its MVC (Model-View-Controller) architecture, you can build dynamic, database-driven applications and master essential concepts for real-world development.

Whether you’re a student or a professional, learning these CodeIgniter fundamentals gives you a solid foundation. You can set up routes, connect to databases, manage sessions, and organize your code with controllers, models, and views.

Next, try building a blog or contact form, explore APIs, or dive into CodeIgniter 4’s advanced features like RESTful services and middleware. CodeIgniter is designed for developers ready to build efficiently and intelligently.

FAQs

1. What is CodeIgniter used for?

CodeIgniter is a PHP framework used to build dynamic web applications quickly and efficiently. It's known for its lightweight structure, MVC architecture, and ease of use, making it ideal for both beginners and professionals.

2. Is CodeIgniter suitable for beginners?

Yes, CodeIgniter is one of the most beginner-friendly PHP frameworks. Its clear folder structure, detailed documentation, and minimal configuration make it perfect for students and developers just starting with web development.

3. How do I install CodeIgniter 4?

You can install CodeIgniter 4 using Composer with the command:

composer create-project codeigniter4/appstarter project-name

Alternatively, you can download it manually from the official website and extract it into your project directory.

4. What are the key differences between CodeIgniter 3 and CodeIgniter 4?

CodeIgniter 4 supports modern PHP features like namespaces, .env files, and built-in CLI tools. It offers improved routing, better security, and test-driven development support, unlike CI 3 which is more legacy-focused.

5. How does MVC architecture work in CodeIgniter?

In CodeIgniter, the MVC architecture separates logic (Model), control flow (Controller), and presentation (View). This helps developers write cleaner, more organized, and maintainable code for larger applications.

6. Can I perform CRUD operations easily in CodeIgniter?

Yes, CodeIgniter simplifies CRUD operations using its Query Builder and Model system. You can insert, update, read, and delete records using simple, secure syntax that avoids raw SQL.

7. How do I connect a database in CodeIgniter?

To connect a database, update the configuration in /app/Config/Database.php. Set the hostname, username, password, and database name. CodeIgniter handles the connection automatically when the model or database class is called.

8. What are helpers and libraries in CodeIgniter?

Helpers are collections of procedural functions (like url_helper), while libraries are class-based tools (like email or session) that offer extended functionality. Both can be autoloaded for global use.

9. Does CodeIgniter support form validation and security?

Absolutely. CodeIgniter provides a powerful Form Validation library and built-in security features like CSRF protection, XSS filtering, and input sanitization to keep your forms and applications secure.

10. Can I use sessions and cookies in CodeIgniter?

Yes, CodeIgniter offers easy-to-use session and cookie management tools. You can store and retrieve session data using built-in methods, and configure cookie behavior through the config files.

11. Is CodeIgniter good for building professional web apps?

Definitely. CodeIgniter is lightweight yet powerful, making it ideal for MVPs, admin panels, CRMs, and small to mid-size web applications. With proper structure and best practices, it's perfectly suited for professional development.

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

text

Foreign Nationals

Disclaimer

  1. The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

  2. The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .