CodeIgniter 3 to 4 Migration: How to Upgrade a CI3 Project
By rightsw · · Updated
If your site runs on CodeIgniter 3, the clock is set by PHP, not by CodeIgniter. CodeIgniter 3.1.13, the last CI3 release, runs on PHP up to 8.1 and breaks on 8.2. PHP 8.1 stopped receiving security fixes at the end of 2025, and most hosts are now moving accounts to 8.2 or newer. A CI3 site is left either running on an unsupported PHP version or on a community fork.
The fix is to migrate to CodeIgniter 4. This guide walks through that migration in the order we would do it, with the CI3 code on one side and its CI4 equivalent on the other.
We covered the previous jump in Upgrading PHP CodeIgniter 2.x to 3.x. This one is bigger: CodeIgniter 4 is a rewrite, not an update.
CodeIgniter 3 vs CodeIgniter 4: what changed
| CodeIgniter 3 | CodeIgniter 4 | |
|---|---|---|
| PHP version | Up to 8.1 (3.1.13) | 8.2+ for 4.7, 8.1 for 4.6.x |
| Install | Download zip | Composer (codeigniter4/appstarter) or zip |
| Web root | Project root, index.php beside application/ |
public/ folder only |
| App folder | application/ |
app/, plus writable/ for logs, cache and sessions |
| Class loading | $this->load->... super-object |
Namespaces, PSR-4 autoloading, new, model(), service() |
| Routing | Auto-routing on by default | Explicit routes; auto-routing off by default |
| Request data | $this->input |
$this->request (IncomingRequest) |
| Output | $this->output |
Response object, returned from the controller |
| Extending core | MY_ classes in application/core |
Your own classes registered in app/Config/Services.php |
| Hooks | $hook[...] |
Events and controller filters |
| CLI | Limited | php spark for migrations, generators, routes and more |
| Status | Final release 3.1.13; not actively developed | Actively maintained |
Before you start: plan the migration
Because nothing carries over automatically, the order matters. This is the sequence that keeps a CI3 to CI4 migration testable at every step:
- Inventory the CI3 app. List controllers, models, libraries, helpers, hooks,
MY_core extensions and third-party packages. Note every place that uses$this->load,$this->input,$this->sessionand$this->db. - Freeze and back up. Tag the CI3 code in version control and take a database dump. You will compare old and new behaviour against these.
- Install a fresh CI4 app next to the old one, on PHP 8.2 or newer.
- Port config (base URL, database, sessions, encryption key) into CI4’s
.envandapp/Config/. - Port the database layer: models first, because everything else depends on them.
- Port controllers and views one module at a time, adding routes as you go.
- Port libraries, helpers, hooks and core extensions.
- Test each module against the CI3 version before moving to the next, then switch the domain over.
For a large application, steps 5 to 7 can run module by module while the CI3 site stays live, with the web server sending finished sections to the CI4 app.
CodeIgniter 4 requirements
PHP and extensions
CodeIgniter 4.7 requires PHP 8.2 or newer. If your server cannot go past PHP 8.1 yet, use the CodeIgniter 4.6.x line, which the CodeIgniter team kept patching for PHP 8.1 users.
Required PHP extensions:
intlmbstring
(json used to be listed too; it is built into PHP 8.)
Optional extensions, depending on what you use:
mysqlndfor MySQLcurlfor the CURLRequest classimagickorgdfor the Image classsimplexmlfor XML formattingmemcache/memcachedorredisfor those cache handlersdom,libxmlandxdebugfor parts of the PHPUnit test helpers
Supported databases
- MySQL via the MySQLi driver (5.1 and above)
- PostgreSQL via the Postgre driver
- SQLite3 via the SQLite3 driver
- Microsoft SQL Server via the SQLSRV driver
- Oracle Database via the OCI8 driver (12.1 and above)
Install CodeIgniter 4
With Composer (recommended)
You need Composer 2.0.14 or later.
composer create-project codeigniter4/appstarter my-app
This creates a my-app folder with the framework in vendor/. If your code lives in Git, vendor/ is normally git-ignored, so run composer install after cloning on a new machine.
Manual download
Download the latest release zip from the codeigniter4/framework releases page and extract it as your project root. Manual installs do not get updates through Composer, so you will have to repeat this for each new version.
Initial configuration
Copy the env file in the project root to .env and set your environment, base URL and database there:
CI_ENVIRONMENT = development
app.baseURL = 'https://example.com/'
database.default.hostname = localhost
database.default.database = my_database
database.default.username = my_user
database.default.password = my_password
database.default.DBDriver = MySQLi
The same settings exist as properties in app/Config/App.php and app/Config/Database.php; values in .env override them.
To drop index.php from your URLs, set $indexPage to an empty string in app/Config/App.php:
public string $indexPage = '';
Point the web server at public/
In CodeIgniter 4 the web server’s document root must be the public/ folder, not the project root. This is a security change: app/, system/ and writable/ are no longer reachable from the browser.
Apache: CI4 ships an .htaccess in public/ that already rewrites requests to index.php. Make sure mod_rewrite is enabled and AllowOverride All is set for that folder. The core of the rule is:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\s\S]*)$ index.php/$1 [L,NC,QSA]
Nginx:
server {
listen 80;
listen [::]:80;
server_name example.com;
root /var/www/example.com/public;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}
error_page 404 /index.php;
location ~ /\. {
deny all;
}
}
Adjust the PHP-FPM socket to match your PHP version.
The new application structure
application/is nowapp/, and the framework lives insystem/(orvendor/codeigniter4/frameworkwith Composer).public/is the web root and holdsindex.phpplus your CSS, JavaScript and images.writable/holds logs, cache, sessions and uploads. The web server needs write access to it.- There is no
application/corefolder. Core extensions work differently (see Extending the framework). - Delete
defined('BASEPATH') OR exit('No direct script access allowed');from every file. CI4 does not defineBASEPATH, so the line now stops every page; and withpublic/as the web root it is not needed. - Everything in
app/is namespaced:App\Controllers,App\Models,App\Librariesand so on.
Upgrade models
Move each model into app/Models/, add a namespace, and extend CodeIgniter\Model instead of CI_Model. You can generate an empty one with php spark make:model UserModel.
CodeIgniter 3:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User_model extends CI_Model
{
public function get_active()
{
return $this->db->where('status', 'active')->get('users')->result();
}
}
CodeIgniter 4:
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $returnType = 'object';
protected $allowedFields = ['name', 'email', 'status'];
public function getActive(): array
{
return $this->where('status', 'active')->findAll();
}
}
$allowedFields matters: CI4’s insert() and update() silently drop any field not listed there, which is a common cause of “the save runs but nothing changes” after a migration.
Load the model with model() or new instead of $this->load->model():
// CI3
$this->load->model('user_model');
$users = $this->user_model->get_active();
// CI4
$users = model('UserModel')->getActive();
// or
$userModel = new \App\Models\UserModel();
Query Builder and result methods
The query builder works much the same, but you start from a table and the result methods are camelCase:
| CodeIgniter 3 | CodeIgniter 4 |
|---|---|
$this->db->get('users') |
$db->table('users')->get() |
->result() |
->getResult() |
->result_array() |
->getResultArray() |
->row() |
->getRow() |
->row_array() |
->getRowArray() |
->num_rows() |
->getNumRows() |
$this->db->insert_id() |
$db->insertID() |
$this->db->affected_rows() |
$db->affectedRows() |
Get the connection with $db = \Config\Database::connect(); or db_connect().
Upgrade controllers
Move each controller into app/Controllers/, add the namespace, and extend BaseController. php spark make:controller Users generates one.
CodeIgniter 3:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends CI_Controller
{
public function index()
{
$this->load->model('user_model');
$data['users'] = $this->user_model->get_active();
$this->load->view('users/index', $data);
}
}
CodeIgniter 4:
<?php
namespace App\Controllers;
class Users extends BaseController
{
public function index(): string
{
$data['users'] = model('UserModel')->getActive();
return view('users/index', $data);
}
}
Note the return. In CI4 a controller returns its output (a string or a Response) instead of echoing it.
The calls you will replace most often
| CodeIgniter 3 | CodeIgniter 4 |
|---|---|
$this->input->post('email') |
$this->request->getPost('email') |
$this->input->get('page') |
$this->request->getGet('page') |
$this->input->ip_address() |
$this->request->getIPAddress() |
$this->uri->segment(3) |
$this->request->getUri()->getSegment(3) |
$this->session->userdata('id') |
session()->get('id') |
$this->session->set_userdata('id', 5) |
session()->set('id', 5) |
$this->session->set_flashdata('msg', 'Saved') |
session()->setFlashdata('msg', 'Saved') |
$this->config->item('base_url') |
config('App')->baseURL |
redirect('login') |
return redirect()->to('login'); |
$this->output->set_content_type('application/json')->set_output(json_encode($data)) |
return $this->response->setJSON($data); |
redirect() is the one that bites most often. In CI3 it ended the script; in CI4 it returns a RedirectResponse, and nothing happens unless you return it.
Upgrade views
Move views into app/Views/. Most view files need very little change:
- Remove the
BASEPATHline if a view has one. - Replace
$this->load->view('folder/file', $data)withreturn view('folder/file', $data); - Where a view loads another view, use
<?= view('partials/header') ?>, or switch to CI4’s view layouts ($this->extend()and$this->section()). - Escape output with
esc():
<html>
<head>
<title><?= esc($title) ?></title>
</head>
<body>
<h1><?= esc($heading) ?></h1>
</body>
</html>
Upgrade routing
Routes live in app/Config/Routes.php. Define one per HTTP verb:
<?php
use CodeIgniter\Router\RouteCollection;
/** @var RouteCollection $routes */
$routes->get('/', 'Home::index');
$routes->get('users', 'Users::index');
$routes->post('users/save', 'Users::save');
$routes->put('users/(:num)', 'Users::update/$1');
$routes->delete('users/(:num)', 'Users::delete/$1');
Auto-routing, which CI3 had on by default, is off in CI4. You can switch it on in app/Config/Routing.php, but CI4’s default “improved” auto-routing expects method names prefixed with the HTTP verb (getIndex(), postSave()), so CI3 controllers will not match without renaming. For most migrations, writing explicit routes is cleaner and safer. Run php spark routes to see every route the app answers.
Class loading: no more super-object
CodeIgniter 3 attached everything to the controller through $this->load. CodeIgniter 4 drops that “super-object”:
- Classes are namespaced and found by PSR-4 autoloading. The
Appnamespace maps toapp/, and Composer packages autoload as usual. - Framework components come from services:
service('email'),service('session'),service('validation'). - Factories (
model(),config()) return a shared instance, much like$this->loaddid. - You can organise code in modules (an HMVC-style layout) by adding namespaces in
app/Config/Autoload.php.
Upgrade libraries
- Your own libraries can stay in
app/Libraries/(addnamespace App\Libraries;), but they can live anywhere the autoloader can find them. - Replace
$this->load->library('cart')with$cart = new \App\Libraries\Cart();. - CI3’s Input class is CI4’s IncomingRequest; CI3’s Output class is CI4’s Response.
- Some CI3 libraries are gone (Calendar, FTP, Javascript, Shopping Cart, Trackback, XML-RPC and Zip Encoding). Replace them with a Composer package or your own class.
Libraries that exist in both versions but changed have their own upgrade notes in the official guide: email, encryption, file uploads, HTML tables, localization, migrations, pagination, responses, routing, security, sessions, validation and the view parser.
One needs care with existing data: encryption. CI4’s Encryption class does not read CI3-encrypted values with its default settings. Since CodeIgniter 4.3 it has configuration options for CI3 compatibility; set those, or decrypt and re-encrypt stored values during the migration.
Upgrade helpers
- Load helpers with
helper('url')orhelper(['url', 'form']), or autoload them inapp/Config/Autoload.php(public $helpers = ['url', 'form'];). - Removed in CI4: the CAPTCHA, Email, Path and Smiley helpers. Replace their functions with your own code or a package.
- The Download helper is gone; instead of
force_download(), return$this->response->download($path, null). - The Language helper is gone, but the
lang()function still works. - The Typography helper became the Typography library.
- The Directory and File helpers merged into the Filesystem helper.
- String helper functions moved into the Text helper.
Upgrade hooks to events and filters
CodeIgniter 4 replaces hooks with events and controller filters:
- Register events in
app/Config/Events.php:
use CodeIgniter\Events\Events;
Events::on('post_controller_constructor', [\App\Libraries\Audit::class, 'log']);
- The
pre_controllerandpost_controllerhook points are gone. Use filters (php spark make:filter AuthFilter) for anything that ran before or after a controller, such as login checks, and attach them to routes inapp/Config/Filters.php. - The
display_overrideandcache_overridehook points were removed along with the methods behind them. post_systemnow runs just before the final page is sent to the browser.
Extending the framework
- There is no
application/corefolder and noMY_prefix convention. - To extend or replace a core class, write your class anywhere the autoloader can see (for example
app/Libraries/MyRequest.php), extend the CI4 class, and return it from the matching method inapp/Config/Services.php. - A common CI3 pattern,
MY_Controllerholding shared logic, maps to putting that logic inapp/Controllers/BaseController.php, which every controller already extends.
Test before you switch over
- Run the CI3 and CI4 apps side by side against a copy of the production database and compare key pages, forms and reports.
- Watch
writable/logs/while testing. CI4 is stricter about undefined variables and types, and the logs show what CI3 used to let through. - Re-check file permissions on
writable/on the production server. - Keep the CI3 release tagged so you can roll back quickly.
Related reading
Frequently asked questions
Can I upgrade CodeIgniter 3 to 4 automatically?
No. CodeIgniter 4 is a complete rewrite with a different structure, namespaces and APIs, and there is no official tool that converts a CI3 project. You install a fresh CI4 app and move your code across, adjusting each file. Your views and SQL usually need the fewest changes; controllers, models and anything using $this->load need the most.
What are the CodeIgniter 4 requirements?
CodeIgniter 4.7 needs PHP 8.2 or newer with the intl and mbstring extensions, plus Composer 2.0.14 or later if you install with Composer. If your server is stuck on PHP 8.1, use the CodeIgniter 4.6.x line. Supported databases are MySQL (5.1+), PostgreSQL, SQLite3, Microsoft SQL Server and Oracle (12.1+).
What is the difference between CodeIgniter 3 and CodeIgniter 4?
CodeIgniter 4 uses namespaces and PSR-4 autoloading, a public/ web root, explicit routing, Composer, a spark command-line tool, filters and events instead of hooks, and request and response objects instead of the CI3 input and output classes. CodeIgniter 3 is no longer actively developed and its last release does not run on PHP 8.2.
What is the latest version of CodeIgniter?
The current line is CodeIgniter 4.7.x (4.7.5 when this guide was updated in October 2026). Check the CodeIgniter 4 releases page for the newest patch release. The final CodeIgniter 3 release is 3.1.13.
How do I download CodeIgniter 4?
The recommended way is Composer: composer create-project codeigniter4/appstarter my-app. For a manual install, download the latest release zip from the codeigniter4/framework releases and point your web server at its public/ folder.
Does CodeIgniter 3 work on PHP 8.2 or 8.3?
Not out of the box. CodeIgniter 3.1.13 runs on PHP up to 8.1. Community forks patch CI3 for PHP 8.2 and later, which can buy time, but they are not maintained by the CodeIgniter team. For a site you plan to keep, migrating to CodeIgniter 4 is the long-term fix.