CodeIgniter: Validation, Filters, Migrations & Spark CLI
Form Validation & CSRF
<?php
public function create()
{
if (!$this->validate([
'title' => 'required|min_length[3]',
'email' => 'required|valid_email',
])) {
return view('articles/create', ['errors' => $this->validator->getErrors()]);
}
$model = new ArticleModel();
$model->insert($this->request->getPost());
return redirect()->to('/articles');
}
<!-- CSRF token required on forms when CSRF protection is enabled
(app/Config/Filters.php) -- guards against Cross-Site Request Forgery -->
<form method="post" action="/articles">
<?= csrf_field() ?>
<input name="title" />
</form>Filters (Middleware-Like)
<?php
// app/Filters/AuthFilter.php -- runs before/after matched routes
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
class AuthFilter implements FilterInterface
{
public function before($request, $arguments = null)
{
if (!session()->get('user_id')) {
return redirect()->to('/login');
}
}
public function after($request, $response, $arguments = null) {}
}
// app/Config/Filters.php -- apply to specific route groups
public array $filters = [
'auth' => ['before' => ['admin/*']],
];Migrations & Spark CLI
# Local dev server
php spark serve
# Scaffolding
php spark make:controller Articles
php spark make:model ArticleModel
php spark make:migration CreateArticlesTable
# Apply/rollback version-controlled schema changes
php spark migrate
php spark migrate:rollback<?php
// app/Database/Migrations/2026-01-01-000000_CreateArticlesTable.php
class CreateArticlesTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => ['type' => 'INT', 'auto_increment' => true],
'title' => ['type' => 'VARCHAR', 'constraint' => 255],
'created_at' => ['type' => 'DATETIME', 'null' => true],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('articles');
}
public function down()
{
$this->forge->dropTable('articles');
}
}Project Structure & .env
public/ is the web server document root -- app source, config, and framework files live outside it, unreachable directly via URL.
.env holds environment-specific config (DB credentials, CI_ENVIRONMENT) kept out of version control -- .env.example is the committed template.
Helpers (helper('form'), helper('url')) are plain procedural utility functions -- form_open(), base_url() -- a lighter pattern than object-oriented Libraries.
A controller can just as easily return $this->response->setJSON($data) as render an HTML view -- the same app can serve pages and a JSON API.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free