Development

Codeigniter Tutorial For Beginners: PHP Web Application Guide

Are you looking to build powerful PHP web applications but feeling overwhelmed by where to start? Well, I’ve got fantastic news for you! Codeigniter is absolutely the framework you need to master. I’ve been using it for years, and I can tell you firsthand that it’s one of the most beginner-friendly yet powerful PHP frameworks out there.

In this comprehensive tutorial, I’ll walk you through everything you need to know to start building amazing web applications with Codeigniter 4, the latest version as of now. No confusing jargon, just straightforward guidance that’ll have you coding like a pro in no time.

What Makes Codeigniter So Special?

Before we dive into the code, let me tell you why Codeigniter stands out from other PHP frameworks:

  • Lightning Fast: Codeigniter is incredibly lightweight and performs much faster than most other frameworks.
  • Easy Learning Curve: The documentation is superb, and the framework follows logical patterns that are easy to grasp.
  • Zero Configuration: You can set up and start developing with minimal configuration.
  • Built-in Security: The framework comes with powerful tools to protect your applications from common web attacks.
  • Community Support: A massive community means you’ll never get stuck on a problem for long.

Trust me, once you start using Codeigniter, you’ll wonder how you ever developed without it!

Prerequisites

Before we begin, make sure you have:

  1. Basic knowledge of PHP (you should understand variables, functions, and object-oriented concepts. Explore our PHP Tutorials to level up your skill!)
  2. Understanding of the MVC design pattern (I’ll explain this more as we go)
  3. A local development environment (XAMPP, WAMP, or similar)
  4. PHP 8.1 or higher installed
  5. Composer installed (the PHP dependency manager)

Understanding MVC Architecture

Codeigniter uses the Model-View-Controller (MVC) pattern, which separates your application into three interconnected components:

  • Models: Handle your data and business logic
  • Views: Display information to users
  • Controllers: Process user requests and coordinate between models and views

This separation makes your code more organized, easier to maintain, and simpler to test. You’ll absolutely love how clean your codebase becomes!

Installing Codeigniter 4

Let’s get started by installing Codeigniter 4. There are two ways to do this:

Method 1: Using Composer (Recommended)

Open your terminal or command prompt and run:

composer create-project codeigniter4/appstarter my-project

This creates a new Codeigniter project named “my-project” in the current directory.

Method 2: Manual Download

  1. Download the latest version from Codeigniter’s official website
  2. Extract the files to your web server’s root directory
  3. Rename the directory to your project name

I strongly recommend using the Composer method as it makes updating Codeigniter much easier in the future.

Directory Structure

After installation, you’ll see the following directory structure:

my-project/
├── app/
│   ├── Config/
│   ├── Controllers/
│   ├── Models/
│   ├── Views/
│   └── ...
├── public/
├── system/
├── writable/
├── tests/
└── vendor/Code language: PHP (php)

Let’s understand what each important directory does:

  • app: This is where all YOUR code goes – controllers, models, views, config files, etc.
  • public: The only directory that should be publicly accessible. Contains index.php and assets like CSS, JS, and images.
  • system: Core framework files – NEVER modify these files directly!
  • writable: Contains files that need write access (logs, cache, etc.)
  • vendor: Contains third-party dependencies

Basic Configuration

Before we start building, let’s configure a few basics:

1. Environment Setup

Rename the env file to .env in your project root. Open it and set:

CI_ENVIRONMENT = development

This enables detailed error reporting during development.

2. Database Configuration

In the .env file, configure your database settings:

database.default.hostname = localhost
database.default.database = my_database
database.default.username = root
database.default.password = your_password
database.default.DBDriver = MySQLiCode language: PHP (php)

3. URL Configuration

Still in the .env file, set your base URL:

app.baseURL = 'http://localhost/my-project/public/'Code language: JavaScript (javascript)

Creating Your First Controller

Controllers are the heart of your application, handling user requests and providing responses. Let’s create our first controller:

  1. Create a file named Blog.php in the app/Controllers directory:
<?php

namespace App\Controllers;

class Blog extends BaseController
{
    public function index()
    {
        echo "Hello World! Welcome to my blog.";
    }
}Code language: HTML, XML (xml)

Now, start your local server and navigate to http://localhost/my-project/public/blog. You should see “Hello World! Welcome to my blog.” This simple controller demonstrates how easy it is to create pages in Codeigniter! 🎉

Tip💡: Explore All CodeIgniter Tutorials by CodeSamplez.com

Working with Views

Displaying raw text isn’t very useful. Let’s create a view to render HTML properly:

  1. Create a directory app/Views/blog
  2. Create a file index.php in this directory:
<!DOCTYPE html>
<html>
<head>
    <title>My Awesome Blog</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        h1 {
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .article {
            margin-bottom: 30px;
            border-bottom: 1px dashed #ccc;
            padding-bottom: 20px;
        }
        .article h2 {
            margin-bottom: 5px;
        }
        .meta {
            color: #777;
            font-size: 0.9em;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <h1>Welcome to My Blog</h1>
    
    <?php foreach($articles as $article): ?>
        <div class="article">
            <h2><?= $article->title ?></h2>
            <div class="meta">By <?= $article->author ?></div>
            <p><?= $article->content ?></p>
        </div>
    <?php endforeach; ?>
</body>
</html>Code language: HTML, XML (xml)
  1. Now, update your controller to use this view:
<?php

namespace App\Controllers;

class Blog extends BaseController
{
    public function index()
    {
        // Data to be passed to the view
        $data = [
            'articles' => [
                (object)[
                    'title' => 'Getting Started with Codeigniter 4',
                    'author' => 'John Doe',
                    'content' => 'Codeigniter 4 is an amazing framework that makes PHP development a breeze.'
                ],
                (object)[
                    'title' => 'MVC Pattern Explained',
                    'author' => 'Jane Smith',
                    'content' => 'The Model-View-Controller pattern separates concerns and makes your code more maintainable.'
                ]
            ]
        ];
        
        // Load the view with data
        return view('blog/index', $data);
    }
}Code language: HTML, XML (xml)

When you refresh the page, you’ll see a nicely formatted blog with two articles. That’s the power of views – they separate your HTML from your PHP logic!

Creating a Model

Models handle your data operations. Let’s create a model to manage our blog articles:

  1. Create a file named BlogModel.php in the app/Models directory:
<?php

namespace App\Models;

use CodeIgniter\Model;

class BlogModel extends Model
{
    // In a real application, you'd connect to a database
    public function getArticles()
    {
        // For now, we'll return dummy data
        return [
            (object)[
                'title' => 'Getting Started with Codeigniter 4',
                'author' => 'John Doe',
                'content' => 'Codeigniter 4 is an amazing framework that makes PHP development a breeze.'
            ],
            (object)[
                'title' => 'MVC Pattern Explained',
                'author' => 'Jane Smith',
                'content' => 'The Model-View-Controller pattern separates concerns and makes your code more maintainable.'
            ],
            (object)[
                'title' => 'Working with Databases in CI4',
                'author' => 'Mike Johnson',
                'content' => 'Codeigniter makes database operations simple with its powerful database library.'
            ]
        ];
    }
}Code language: HTML, XML (xml)
  1. Update your controller to use this model:
<?php

namespace App\Controllers;

use App\Models\BlogModel;

class Blog extends BaseController
{
    public function index()
    {
        // Create an instance of the model
        $model = new BlogModel();
        
        // Get data from the model
        $data = [
            'articles' => $model->getArticles()
        ];
        
        // Load the view with data
        return view('blog/index', $data);
    }
}Code language: HTML, XML (xml)

Working with a Real Database

Now let’s upgrade our model to use a real database:

  1. Create a database table:
CREATE TABLE articles (
    id INT(11) PRIMARY KEY AUTO_INCREMENT,
    title VARCHAR(255) NOT NULL,
    author VARCHAR(100) NOT NULL,
    content TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO articles (title, author, content) VALUES
('Getting Started with Codeigniter 4', 'John Doe', 'Codeigniter 4 is an amazing framework that makes PHP development a breeze.'),
('MVC Pattern Explained', 'Jane Smith', 'The Model-View-Controller pattern separates concerns and makes your code more maintainable.'),
('Working with Databases in CI4', 'Mike Johnson', 'Codeigniter makes database operations simple with its powerful database library.');Code language: PHP (php)
  1. Update your model to use the database:
<?php

namespace App\Models;

use CodeIgniter\Model;

class BlogModel extends Model
{
    protected $table = 'articles';
    protected $primaryKey = 'id';
    protected $allowedFields = ['title', 'author', 'content'];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';
    
    // No need for a custom getArticles method - we can use the built-in findAll()
}Code language: HTML, XML (xml)
  1. Update your controller:
<?php

namespace App\Controllers;

use App\Models\BlogModel;

class Blog extends BaseController
{
    public function index()
    {
        $model = new BlogModel();
        
        $data = [
            'articles' => $model->findAll()
        ];
        
        return view('blog/index', $data);
    }
}Code language: HTML, XML (xml)

That’s it! Codeigniter’s model system makes database operations incredibly simple. You get all the CRUD (Create, Read, Update, Delete) operations without writing a single SQL query!

Creating Forms and Handling Input

Let’s add functionality to create new blog posts:

  1. Create a new view app/Views/blog/create.php:
<!DOCTYPE html>
<html>
<head>
    <title>Create New Article</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        h1 {
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
        }
        input[type="text"], textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
        }
        textarea {
            height: 150px;
        }
        button {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 10px 15px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Create New Article</h1>
    
    <?php if(session()->getFlashdata('error')): ?>
        <div style="color: red; margin-bottom: 15px;">
            <?= session()->getFlashdata('error') ?>
        </div>
    <?php endif; ?>
    
    <form action="<?= site_url('blog/store') ?>" method="post">
        <div class="form-group">
            <label for="title">Title</label>
            <input type="text" name="title" id="title" required>
        </div>
        
        <div class="form-group">
            <label for="author">Author</label>
            <input type="text" name="author" id="author" required>
        </div>
        
        <div class="form-group">
            <label for="content">Content</label>
            <textarea name="content" id="content" required></textarea>
        </div>
        
        <button type="submit">Create Article</button>
    </form>
    
    <p><a href="<?= site_url('blog') ?>">Back to Articles</a></p>
</body>
</html>Code language: HTML, XML (xml)
  1. Add methods to your controller:
// In Blog.php controller

public function create()
{
    return view('blog/create');
}

public function store()
{
    // Validate input
    $rules = [
        'title' => 'required|min_length[3]|max_length[255]',
        'author' => 'required|min_length[3]|max_length[100]',
        'content' => 'required|min_length[10]'
    ];
    
    if (!$this->validate($rules)) {
        return redirect()->back()->withInput()->with('error', $this->validator->getErrors());
    }
    
    // Get form data
    $data = [
        'title' => $this->request->getPost('title'),
        'author' => $this->request->getPost('author'),
        'content' => $this->request->getPost('content')
    ];
    
    // Save to database
    $model = new BlogModel();
    $model->insert($data);
    
    // Redirect to blog list
    return redirect()->to('/blog')->with('message', 'Article created successfully!');
}Code language: PHP (php)
  1. Add a link to the create page in your index view:
<!-- Add this near the top of app/Views/blog/index.php -->
<p><a href="<?= site_url('blog/create') ?>">Create New Article</a></p>

<!-- And add this to display success message -->
<?php if(session()->getFlashdata('message')): ?>
    <div style="background: #d4edda; color: #155724; padding: 10px; margin-bottom: 20px;">
        <?= session()->getFlashdata('message') ?>
    </div>
<?php endif; ?>Code language: HTML, XML (xml)

Routes

Codeigniter 4 offers powerful routing capabilities. Let’s configure some routes to make our URLs cleaner:

  1. Open app/Config/Routes.php and add:
$routes->get('blog', 'Blog::index');
$routes->get('blog/create', 'Blog::create');
$routes->post('blog/store', 'Blog::store');
$routes->get('blog/(:num)', 'Blog::show/$1');Code language: PHP (php)

This allows URLs like:

  • http://localhost/my-project/public/blog for the index
  • http://localhost/my-project/public/blog/create to create an article
  • http://localhost/my-project/public/blog/1 to view article #1

Handling AJAX Requests

Want to add some interactivity? Here’s how to handle AJAX requests in Codeigniter:

  1. Add a new method to your controller:
public function like($id)
{
    // In a real app, you'd update a likes count in the database
    
    // For now, just return a response
    return $this->response->setJSON(['success' => true, 'likes' => rand(5, 100)]);
}Code language: PHP (php)
  1. Add some JavaScript to your view:
<!-- Add this to your index.php view, before the closing body tag -->
<script>
function likeArticle(id) {
    fetch(`<?= site_url('blog/like') ?>/${id}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById(`likes-${id}`).textContent = data.likes;
            }
        });
}
</script>

<!-- And modify your article display to add a like button -->
<div class="article">
    <h2><?= $article->title ?></h2>
    <div class="meta">
        By <?= $article->author ?> | 
        <span id="likes-<?= $article->id ?>">0</span> likes
        <button onclick="likeArticle(<?= $article->id ?>)">Like</button>
    </div>
    <p><?= $article->content ?></p>
</div>Code language: HTML, XML (xml)

Using Helper Functions

Codeigniter comes with many helper functions to simplify common tasks. Let’s use some:

  1. Load helpers in your controller:
// In Blog.php controller constructor or method
helper(['form', 'url']);Code language: JavaScript (javascript)
  1. Now you can use helper functions in your views:
<!-- Instead of -->
<form action="<?= site_url('blog/store') ?>" method="post">

<!-- You can write -->
<form action="<?= site_url('blog/store') ?>" method="post">
    <?= csrf_field() ?> <em><!-- Adds CSRF protection token --></em>
    
    <!-- Form inputs here -->
    <?= form_submit('submit', 'Create Article', ['class' => 'button']) ?>
</form>Code language: HTML, XML (xml)

Adding Authentication

Most web applications need authentication. Let’s implement basic login/registration:

  1. Install the Shield authentication module (Codeigniter’s official auth solution):
composer require codeigniter4/shieldCode language: JavaScript (javascript)
  1. Run the migrations:
php spark shield:setup
php spark migrateCode language: CSS (css)
  1. Create a route group with authentication:
// In app/Config/Routes.php
$routes->group('admin', ['filter' => 'auth'], function($routes) {
    $routes->get('dashboard', 'Admin::dashboard');
    // Other protected routes here
});Code language: PHP (php)

This ensures only authenticated users can access the admin section!

Tips for Debugging

Codeigniter offers excellent tools for debugging your application:

  1. Enable debug toolbar by setting:
CI_ENVIRONMENT = development
  1. Use the debug bar to inspect:
    • Request and response data
    • Database queries
    • Performance metrics
    • Loaded files
    • And much more!
  2. For logging custom messages:
log_message('debug', 'This is a debug message');
log_message('error', 'Something went wrong!');Code language: JavaScript (javascript)

Common Pitfalls to Avoid

As you develop with Codeigniter, watch out for these common mistakes:

  • Forgetting namespaces: Always include the correct namespace for your models and controllers.
  • Direct model property access: Use getter and setter methods instead of direct property access:
// Incorrect 
$article->title = 'New Title'; 
// Correct 
$article->setTitle('New Title');Code language: PHP (php)
  • Not escaping output: Always use the esc() function to prevent XSS attacks: php<?= esc($article->title) ?>
  • Ignoring validation: Always validate user input before processing it.

Best Practices for Codeigniter Development

To get the most out of Codeigniter, follow these best practices:

  1. Use environment files: Keep sensitive data (like API keys) in .env files.
  2. Create Base Controllers: Extend BaseController for common functionality across controllers.
  3. Use Services: Leverage Codeigniter’s service system for dependency injection.
  4. Organize Business Logic: Keep heavy logic in models or services, not controllers.
  5. Use Migrations: Use database migrations for version control of your database structure.

Conclusion

Congratulations! You’ve now mastered the basics of Codeigniter development. This incredibly powerful framework makes PHP development faster, more secure, and much more enjoyable. From creating simple blogs to complex applications, Codeigniter has absolutely everything you need.

Remember, the best way to learn is by doing. Take what you’ve learned in this tutorial and start building your own projects. The more you practice, the more comfortable you’ll become with the framework.

And don’t forget – the official Codeigniter documentation is your best friend. It’s comprehensive, well-written, and updated regularly.

Happy coding with Codeigniter! If you found this tutorial helpful, please share it with others who might benefit from it.

Rana Ahsan

Rana Ahsan is a seasoned software engineer and technology leader specialized in distributed systems and software architecture. With a Master’s in Software Engineering from Concordia University, his experience spans leading scalable architecture at Coursera and TopHat, contributing to open-source projects. This blog, CodeSamplez.com, showcases his passion for sharing practical insights on programming and distributed systems concepts and help educate others. Github | X | LinkedIn

View Comments

  • First example works but the rest of the examples are lacking file names, etc. so not of much use as a beginner tutorial.

    • The first section does work, then the rest of the article becomes unclear.

      1. In the section "Create a model", what should be the filename of that file?
      2. In the section "Create A View", what should be the filename of that?

      • Hi MichaelB, There is no specific restriction to the naming convention for model/view(or even controller). You can use any name, just you will have to remember to extend them from their corresponding base class. Like, if you are creating a model, you must have to inherit the "CI_Model" class, to get the characteristics of a regular Codeigniter model. In case of view, just name the template any name and then call it from controller with data(if any), Like as follows:

        $this->load->view("template_name",$data);

        I will edit the tutorial for calling a view from controller. Seems it will may helpful to some other guys like you. Thanks for pointing out is.

  • Really great programming abilities you\'ve there. i\'m a programmer myself but I still require to learn until I reach your ability. great article!

  • thank you very much
    it give me complete inside out to the MVC as well as codeignighter
    thanks you very very much

  • this helped me a lot buddy and moreover your site interface is really good and CLEAN.

    keep up the good work.

  • hi rana, i have problem with include php file. i use include(), require() and require_once(). but none of them works.
    i have a php file that contain only variables, so much variables. and i want to include the file to passing variables.
    how i supposed to do. pls help me.
    the ci directory:
    -application
    -system
    -user_guide
    -style
    -include_folder

    and my file in include_folder directory.

    thanks in advance.

  • hello Rana,
    I'm a beginer in CI my problem is how to load jquery library in the current version of CI and how to apply a common CSS styling sheet to all my views

Recent Posts

Service Workers in React: Framework Integration Guide

Learn how to integrate service workers in React, Next.js, Vue, and Angular with practical code examples and production-ready implementations for modern web applications.

2 weeks ago

Service Worker Caching Strategies: Performance & Offline Apps

Master the essential service worker caching strategies that transform web performance. Learn Cache-First, Network-First, and Stale-While-Revalidate patterns with practical examples that'll make your apps blazingly…

3 weeks ago

Service Worker Lifecycle: Complete Guide for FE Developers

Master the intricate dance of service worker states and events that power modern PWAs. From registration through installation, activation, and termination, understanding the lifecycle unlocks…

4 weeks ago

This website uses cookies.