CodeIgniter 4: Building Web Applications with PHP
CodeIgniter 4 is a lightweight PHP framework designed for building modern web applications. It provides a structured development environment with routing, controllers, models, views, database integration, validation, sessions, and other tools that help make PHP application development more organized and maintainable.
In this guide, we will explore the fundamentals of CodeIgniter 4, from project setup and MVC architecture to database integration, CRUD operations, forms, authentication, and common development problems.
What is CodeIgniter?
CodeIgniter is an open-source PHP framework that provides tools and libraries for building web applications.
Instead of placing all application logic inside a small number of PHP files, CodeIgniter provides a structured architecture that helps developers separate different responsibilities.
Why Use CodeIgniter?
- Lightweight PHP framework
- Simple project structure
- Built-in routing system
- Database support
- Form validation
- Session management
- MVC architecture
- Reusable application components
CodeIgniter vs Plain PHP
Plain PHP gives developers complete control over their application, but larger projects can become difficult to organize when everything is placed inside a small number of files.
CodeIgniter provides a framework structure that helps separate application logic, database operations, user interfaces, routing, and configuration.
MVC Architecture
CodeIgniter uses the Model-View-Controller architecture to separate different responsibilities of an application.
- Model - responsible for data and database operations.
- View - responsible for the user interface.
- Controller - handles requests and coordinates application logic.
User
↓
Route
↓
Controller
↓
Model
↓
Database
↓
Controller
↓
View
↓
User
Installing CodeIgniter
A CodeIgniter project can be created using Composer. Make sure PHP and Composer are installed on your development machine.
composer create-project codeigniter4/appstarter myapp
Enter the project directory:
cd myapp
Start the CodeIgniter development server:
php spark serve
Project Folder Structure
myapp/
│
├── app/
│ ├── Config/
│ ├── Controllers/
│ ├── Models/
│ ├── Views/
│ └── Database/
│
├── public/
├── writable/
├── tests/
├── system/
├── env
└── spark
Creating a Controller
Controllers receive requests and determine what the application should do.
Create a controller inside the
app/Controllers directory.
<?php
namespace App\Controllers;
class Home extends BaseController
{
public function index()
{
return view('home');
}
}
Creating a View
Views contain the HTML interface displayed to the user.
<!DOCTYPE html>
<html>
<head>
<title>My CodeIgniter App</title>
</head>
<body>
<h1>Welcome to CodeIgniter 4</h1>
</body>
</html>
Routing
Routes determine which controller method should handle a specific URL.
Routes can be configured inside:
app/Config/Routes.php.
$routes->get('/', 'Home::index');
Request and Response Flow
Browser Request
↓
Route
↓
Controller
↓
Application Logic
↓
Model
↓
Database
↓
Controller
↓
View
↓
HTTP Response
Connecting CodeIgniter to MySQL
CodeIgniter can connect to MySQL using its database configuration.
database.default.hostname = localhost
database.default.database = my_database
database.default.username = root
database.default.password =
database.default.DBDriver = MySQLi
Creating a Model
Models are commonly used to interact with database tables.
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = [
'name',
'email',
'password'
];
}
Query Builder
CodeIgniter provides Query Builder functionality for building database queries using PHP methods.
$builder = $this->db->table('users');
$query = $builder
->where('email', $email)
->get();
$user = $query->getRow();
CRUD Operations
CRUD stands for Create, Read, Update, and Delete. These operations form the foundation of many database-driven applications.
Create
$userModel->insert([
'name' => $name,
'email' => $email
]);
Read
$users = $userModel->findAll();
Update
$userModel->update($id, [
'name' => $name
]);
Delete
$userModel->delete($id);
Creating Forms
Forms allow users to submit information to the application.
<form method="post" action="/users/create">
<label>Name</label>
<input type="text" name="name">
<label>Email</label>
<input type="email" name="email">
<button type="submit">
Save
</button>
</form>
Form Submission
$name = $this->request->getPost('name');
$email = $this->request->getPost('email');
Input Validation
User input should always be validated before it is processed or stored.
$rules = [
'name' => 'required|min_length[3]',
'email' => 'required|valid_email'
];
if (!$this->validate($rules)) {
return redirect()
->back()
->withInput();
}
Authentication
Authentication allows an application to identify users and control access to protected resources.
- Login form
- User database
- Password hashing
- Session management
- Logout functionality
- User access control
Password Hashing
Passwords should never be stored as plain text.
$hash = password_hash(
$password,
PASSWORD_DEFAULT
);
Sessions
$session = session();
$session->set([
'user_id' => $user['id'],
'logged_in' => true
]);
User Access Control
if (!session()->get('logged_in')) {
return redirect()->to('/login');
}
Mini Project: Simple CRUD Application
A good way to learn CodeIgniter is to build a small CRUD application connected to MySQL.
Browser
↓
User Management Page
↓
Controller
↓
UserModel
↓
MySQL
↓
UserModel
↓
Controller
↓
View
Common Problems
Routing Errors
If a URL does not reach the expected controller, check the route definition and controller method name.
Database Connection Problems
Verify the database hostname, database name, username, password, and database driver.
Incorrect Controller Paths
Make sure controllers are located inside the correct application directory and use the correct namespace.
Validation Errors
Check the validation rules and make sure submitted form fields match the expected field names.
Session Issues
Check the session configuration when authentication state does not persist correctly.
Best Practices
- Keep controllers focused on request handling
- Use models for database operations
- Keep views focused on presentation
- Validate user input
- Use password hashing
- Protect sensitive configuration
- Use reusable components
- Keep dependencies updated
- Log application errors appropriately
- Test applications before deployment
Recommended Application Architecture
CodeIgniter 4 Application
│
├── Controllers
│ ↓
│ Request Handling
│
├── Models
│ ↓
│ Database Operations
│
├── Views
│ ↓
│ User Interface
│
├── Config
│ ↓
│ Application Settings
│
└── Database
↓
MySQL
When Should You Use CodeIgniter?
CodeIgniter can be useful for developers who want a lightweight PHP framework with a structured architecture for building web applications.
It can be used for CRUD systems, administrative dashboards, authentication systems, database-driven websites, internal applications, APIs, and other PHP-based projects.
Conclusion
CodeIgniter 4 provides a structured environment for building PHP applications without requiring developers to manage every architectural component manually.
By understanding MVC, routing, controllers, models, views, database integration, CRUD operations, validation, sessions, and authentication, developers can build more organized and maintainable PHP applications.
📖 1,033 Words