🔥

CodeIgniter

Development Frameworks

Moralo o bobebe oa PHP o nang le sebaka se senyenyane sa ho haha likopo tsa webo

Deployment Info

Ho romelloa ha basebetsi: 2-5 min
sehlopha: Development Frameworks
Tšehetso: 24/7

Share this guide

Overview

CodeIgniter is a powerful, lightweight PHP framework with a small footprint that helps you build full-featured web applications quickly and efficiently. Known for its simplicity, excellent performance, and minimal configuration requirements, CodeIgniter has been a favorite among developers who value pragmatic solutions over complex architectural patterns.

What sets CodeIgniter apart is its incredibly small download size (around 2MB) and exceptional speed. The framework has minimal dependencies and doesn't require you to learn a complex templating language or adhere to strict coding conventions. You can write PHP naturally, mixing logic and presentation as needed, or use the built-in templating system if you prefer separation. This flexibility makes CodeIgniter ideal for rapid prototyping and projects where you need to get up and running quickly.

The framework follows the Model-View-Controller (MVC) architectural pattern loosely, giving you the freedom to use it strictly or adapt it to your needs. You can build entire applications without models if your project doesn't require them, or use the full MVC structure for larger applications. CodeIgniter doesn't force architectural decisions on you - it provides tools and lets you choose how to use them.

CodeIgniter comes with an extensive library collection that handles common tasks like database interaction, form validation, session management, email sending, image manipulation, file uploads, and pagination. The database abstraction layer supports multiple database systems (MySQL, PostgreSQL, SQLite, MSSQL) with a consistent Active Record pattern that makes database operations clean and secure. Query Builder provides protection against SQL injection while keeping queries readable and maintainable.

Security is built into CodeIgniter's core. Input data is automatically filtered, XSS protection can be enabled globally, CSRF protection guards against cross-site request forgery, and password hashing uses bcrypt by default. The framework encourages secure coding practices without requiring security expertise, making it easier to build applications that are safe from common web vulnerabilities.

Documentation is one of CodeIgniter's strongest points. The user guide is comprehensive, well-organized, and includes practical examples for every feature. Whether you're a beginner learning web development or an experienced developer picking up CodeIgniter for the first time, you'll find the documentation clear and helpful. The framework also has a large, active community that provides support, tutorials, and third-party packages.

Performance is exceptional out of the box. CodeIgniter has minimal overhead, efficient code execution, and intelligent caching systems that make applications fast without optimization. The framework loads only the components you need for each request, keeping memory usage low and response times quick. For high-traffic applications, CodeIgniter scales well with proper database optimization and caching strategies.

Whether you're building a simple blog, RESTful API, e-commerce site, or complex business application, CodeIgniter provides the tools you need without the bloat. It's particularly well-suited for shared hosting environments, legacy PHP versions (though CodeIgniter 4 requires PHP 7.4+), and projects where simplicity and performance are priorities over architectural purity.

Key Features

Lightweight & Fast

Small footprint (2MB), minimal overhead, and exceptional performance with only essential components loaded

Minimal Configuration

Nearly zero-config setup with sensible defaults - start coding immediately without complex configuration

MVC Architecture (Flexible)

Loosely follows MVC pattern with freedom to adapt to your needs - use full MVC or simplified approach

Built-in Security Features

XSS filtering, CSRF protection, password hashing, input validation, and SQL injection prevention

Comprehensive Library Collection

Rich set of libraries for database, email, sessions, forms, file uploads, pagination, and more

Excellent Documentation

Clear, comprehensive user guide with practical examples and active community support

Mehlala ea ho sebelisa

• **Small to Medium Web Applications**: Blogs, portfolios, business websites, and content management systems
• **RESTful APIs**: Build JSON/XML APIs for mobile apps, SPAs, or third-party integrations
• **Rapid Prototyping**: Quickly validate ideas and build MVPs with minimal setup time
• **Legacy System Modernization**: Modernize older PHP applications while maintaining simple architecture
• **Shared Hosting Projects**: Works well on budget shared hosting with older PHP versions
• **Learning Web Development**: Great for beginners learning MVC patterns and PHP frameworks
• **E-commerce Platforms**: Build shopping carts, product catalogs, and payment integrations

Installation Guide

**Installation on Ubuntu 22.04 LTS (CodeIgniter 4):**

**1. Install PHP and Extensions:**
```bash
sudo apt update
sudo apt install php8.1 php8.1-{fpm,cli,mysql,mbstring,xml,curl,intl,zip,gd} -y
```

**2. Install Composer:**
```bash
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
```

**3. Install CodeIgniter via Composer:**
```bash
cd /var/www
composer create-project codeigniter4/appstarter myproject
cd myproject
```

**4. Set Permissions:**
```bash
sudo chown -R www-data:www-data /var/www/myproject
sudo chmod -R 755 /var/www/myproject
sudo chmod -R 777 /var/www/myproject/writable
```

**5. Configure Environment:**
```bash
cp env .env
nano .env
```

Set configuration:
```env
CI_ENVIRONMENT = development

database.default.hostname = localhost
database.default.database = mydb
database.default.username = dbuser
database.default.password = dbpass
database.default.DBDriver = MySQLi
```

**6. Configure Apache Virtual Host:**
```bash
sudo nano /etc/apache2/sites-available/myproject.conf
```

Add:
```apache
<VirtualHost *:80>
ServerName myproject.local
DocumentRoot /var/www/myproject/public

<Directory /var/www/myproject/public>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

ErrorLog ${APACHE_LOG_DIR}/myproject_error.log
CustomLog ${APACHE_LOG_DIR}/myproject_access.log combined
</VirtualHost>
```

Enable site:
```bash
sudo a2ensite myproject.conf
sudo a2enmod rewrite
sudo systemctl restart apache2
```

**7. Or Configure Nginx:**
```bash
sudo nano /etc/nginx/sites-available/myproject
```

Add:
```nginx
server {
listen 80;
server_name myproject.local;
root /var/www/myproject/public;
index index.php index.html;

location / {
try_files $uri $uri/ /index.php?$query_string;
}

location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
```

Enable:
```bash
sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

**8. Install MySQL and Create Database:**
```bash
sudo apt install mysql-server -y
sudo mysql

CREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'dbuser'@'localhost' IDENTIFIED BY 'dbpass';
GRANT ALL PRIVILEGES ON mydb.* TO 'dbuser'@'localhost';
FLUSH PRIVILEGES;
EXIT;
```

**9. Run Migrations (if using):**
```bash
php spark migrate
```

**10. Test Installation:**
Visit http://myproject.local in browser - you should see CodeIgniter welcome page

**Quick Start with Built-in Server (Development):**
```bash
php spark serve
# Visit http://localhost:8080
```

Configuration Tips

**Essential Configuration:**

**1. Environment Configuration (.env):**
```env
# Environment
CI_ENVIRONMENT = production # development, testing, production

# Base URL
app.baseURL = 'https://yourdomain.com/'

# Database
database.default.hostname = localhost
database.default.database = mydb
database.default.username = dbuser
database.default.password = secure_password
database.default.DBDriver = MySQLi
database.default.DBPrefix =

# Encryption
encryption.key = your-encryption-key-here # Generate: php spark key:generate
```

**2. Routes Configuration (app/Config/Routes.php):**
```php
<?php
$routes->get('/', 'Home::index');
$routes->get('blog', 'Blog::index');
$routes->get('blog/(:segment)', 'Blog::view/$1');

// RESTful API routes
$routes->resource('api/users');

// Group routes
$routes->group('admin', ['filter' => 'auth'], function($routes) {
$routes->get('dashboard', 'Admin\Dashboard::index');
$routes->resource('posts');
});
```

**3. Database Configuration (app/Config/Database.php):**
```php
<?php
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'mydb',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_general_ci',
];
```

**4. Controller Example:**
```php
<?php
namespace App\Controllers;

class Blog extends BaseController
{
protected $blogModel;

public function __construct()
{
$this->blogModel = model('BlogModel');
}

public function index()
{
$data = [
'posts' => $this->blogModel->paginate(10),
'pager' => $this->blogModel->pager
];

return view('blog/index', $data);
}

public function view($slug)
{
$post = $this->blogModel->where('slug', $slug)->first();

if (!$post) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
}

return view('blog/view', ['post' => $post]);
}
}
```

**5. Model Example with Validation:**
```php
<?php
namespace App\Models;

use CodeIgniter\Model;

class BlogModel extends Model
{
protected $table = 'posts';
protected $primaryKey = 'id';
protected $allowedFields = ['title', 'slug', 'body', 'author_id'];
protected $useTimestamps = true;

protected $validationRules = [
'title' => 'required|min_length[3]|max_length[255]',
'slug' => 'required|is_unique[posts.slug]',
'body' => 'required'
];

protected $validationMessages = [
'title' => [
'required' => 'Title is required',
'min_length' => 'Title must be at least 3 characters'
]
];
}
```

**6. Form Validation:**
```php
<?php
// In controller
public function create()
{
$validation = \Config\Services::validation();

$validation->setRules([
'email' => 'required|valid_email|is_unique[users.email]',
'password' => 'required|min_length[8]',
'confirm' => 'required|matches[password]'
]);

if (!$validation->withRequest($this->request)->run()) {
return view('register', ['validation' => $validation]);
}

// Save user
}
```

**7. Working with Database (Query Builder):**
```php
<?php
// Select
$users = $db->table('users')
->select('id, name, email')
->where('status', 'active')
->orderBy('name', 'ASC')
->get()
->getResultArray();

// Insert
$data = ['name' => 'John', 'email' => 'john@example.com'];
$db->table('users')->insert($data);

// Update
$db->table('users')
->where('id', 1)
->update(['status' => 'inactive']);

// Delete
$db->table('users')->where('id', 1)->delete();

// Join
$results = $db->table('posts')
->join('users', 'users.id = posts.author_id')
->get()
->getResult();
```

**8. Sessions and Authentication:**
```php
<?php
// Start session
$session = session();

// Set session data
$session->set('user_id', 123);
$session->set('logged_in', true);

// Get session data
$userId = $session->get('user_id');

// Flash data (available only on next request)
$session->setFlashdata('success', 'Login successful!');

// Destroy session
$session->destroy();
```

**9. Caching:**
```php
<?php
$cache = \Config\Services::cache();

// Save to cache
$cache->save('user_123', $userData, 3600); // 1 hour

// Get from cache
$data = $cache->get('user_123');

// Delete from cache
$cache->delete('user_123');

// Clear all cache
$cache->clean();
```

**10. CLI Commands (Spark):**
```bash
# Run migrations
php spark migrate

# Rollback migrations
php spark migrate:rollback

# Create migration
php spark make:migration CreateUsersTable

# Create controller
php spark make:controller Blog

# Create model
php spark make:model BlogModel

# Run seeder
php spark db:seed UserSeeder

# Clear cache
php spark cache:clear
```

**Best Practices:**
- Use environment variables for sensitive configuration
- Enable CSRF protection in production
- Use password_hash() for passwords (built-in with shield library)
- Validate and sanitize all user inputs
- Use prepared statements (Query Builder does this automatically)
- Keep writable/ directory outside document root in production
- Enable error logging and disable error display in production
- Use migrations for database schema management
- Implement proper error handling and logging
- Use caching for frequently accessed data

Lekanya Sengoloa sena

-
Loading...

Na o se o loketse ho kenya kopo ya hao? ?

Get started in minutes with our simple VPS deployment process

Ha ho hlokahale karete ea mokitlane bakeng sa ho ingolisa • Kenya ka metsotso e 2-5