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.
Before we dive into the code, let me tell you why Codeigniter stands out from other PHP frameworks:
Trust me, once you start using Codeigniter, you’ll wonder how you ever developed without it!
Before we begin, make sure you have:
Codeigniter uses the Model-View-Controller (MVC) pattern, which separates your application into three interconnected components:
This separation makes your code more organized, easier to maintain, and simpler to test. You’ll absolutely love how clean your codebase becomes!
Let’s get started by installing Codeigniter 4. There are two ways to do this:
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.
I strongly recommend using the Composer method as it makes updating Codeigniter much easier in the future.
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:
Before we start building, let’s configure a few basics:
Rename the env
file to .env
in your project root. Open it and set:
CI_ENVIRONMENT = development
This enables detailed error reporting during development.
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 = MySQLi
Code language: PHP (php)
Still in the .env
file, set your base URL:
app.baseURL = 'http://localhost/my-project/public/'
Code language: JavaScript (javascript)
Controllers are the heart of your application, handling user requests and providing responses. Let’s create our first controller:
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
Displaying raw text isn’t very useful. Let’s create a view to render HTML properly:
app/Views/blog
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)
<?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!
Models handle your data operations. Let’s create a model to manage our blog articles:
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)
<?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)
Now let’s upgrade our model to use a real database:
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)
<?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)
<?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!
Let’s add functionality to create new blog posts:
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)
// 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)
<!-- 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)
Codeigniter 4 offers powerful routing capabilities. Let’s configure some routes to make our URLs cleaner:
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 indexhttp://localhost/my-project/public/blog/create
to create an articlehttp://localhost/my-project/public/blog/1
to view article #1Want to add some interactivity? Here’s how to handle AJAX requests in Codeigniter:
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)
<!-- 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)
Codeigniter comes with many helper functions to simplify common tasks. Let’s use some:
// In Blog.php controller constructor or method
helper(['form', 'url']);
Code language: JavaScript (javascript)
<!-- 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)
Most web applications need authentication. Let’s implement basic login/registration:
composer require codeigniter4/shield
Code language: JavaScript (javascript)
php spark shield:setup
php spark migrate
Code language: CSS (css)
// 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!
Codeigniter offers excellent tools for debugging your application:
CI_ENVIRONMENT = development
log_message('debug', 'This is a debug message');
log_message('error', 'Something went wrong!');
Code language: JavaScript (javascript)
As you develop with Codeigniter, watch out for these common mistakes:
// Incorrect
$article->title = 'New Title';
// Correct
$article->setTitle('New Title');
Code language: PHP (php)
esc()
function to prevent XSS attacks: php<?= esc($article->title) ?>
To get the most out of Codeigniter, follow these best practices:
.env
files.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.
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.
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…
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…
This website uses cookies.
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.
Are you having issues? Can you please explain what? Then I can try to solve it and also update the tutorial for being more helpful for future seekers. Thanks..
Thanks for this...Like it
Nice One. Thanks..
the name of the file should be similar to its class name,
for example if we have a class blog the controller should be blog.php this way you will not get error.
How to create new controller.
Hi, Please refer to "Create A Basic Controller" section. Please let me know f you don't understand anything..
Thanks Rana. Then i have another doubt how to create admin for cms. I created admin folder in controller. If i typed browser i have error page not found. What i do Rana.
Hi, well, you will have to study a little about how codeigniter urls work and also how you can customize the routing. Seems like, you are facing issue similar to this one: http://stackoverflow.com/questions/8143997/codeigniter-2-0-x-controller-subdirectories-default-controller-needs-to-be-in . There is a solution already, refer to that. Hope these helps. Thanks.
that's good
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!
Wow, nice post buddy. It can help me to develop website using codeigniter framework.
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.
try using:
APPPATH."/include_folder/file_name.php"
it vary good for fresher + inretmideate
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