Migrating CodeIgniter 3 to 4 Without a Rewrite
CI4 is not an upgrade of CI3, it is a different framework with a similar name. Here is the honest map of the gap and a staged plan that keeps the app running.
The request usually arrives as "we need to upgrade CodeIgniter". Be blunt early: there is no upgrade. CodeIgniter 4 shares a name, a philosophy and a query builder with CodeIgniter 3 and almost nothing else - no in-place update path, no compatibility layer, no shim. What there is, is a well-understood gap you can cross one route group at a time without taking the business offline.
What actually differs
CI3 loads things. Every controller inherits CI_Controller and everything else arrives through $this->load->model(), $this->load->library(), $this->load->view(). No namespaces: the framework is a set of globals and a loader.
CI4 is namespaced and PSR-4 autoloaded. Controllers live in app/Controllers under App\Controllers, models in app/Models under App\Models, and you pull a class in by importing it. The document root moves too - CI4 serves only public/, with public/index.php as the front controller and the application code above the web root. That is a web-server change rather than a code change, and on shared hosting it is sometimes the hardest single step in the project.
// application/controllers/Blog.php (CI3)
defined('BASEPATH') OR exit('No direct script access allowed');
class Blog extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('post_model');
$this->load->helper('url');
}
public function post($id = null) {
$post = $this->post_model->get($id);
if (!$post) {
show_404();
}
$data = array(
'post' => $post,
'comment' => $this->input->post('comment'),
);
$this->load->view('templates/header', $data);
$this->load->view('blog/post', $data);
$this->load->view('templates/footer');
}
}
// app/Controllers/Blog.php (CI4)
namespace App\Controllers;
use App\Models\PostModel;
use CodeIgniter\Exceptions\PageNotFoundException;
class Blog extends BaseController {
public function post($id = null) {
$post = (new PostModel())->find($id);
if (!$post) {
throw PageNotFoundException::forPageNotFound();
}
return view('blog/post', [
'post' => $post,
'comment' => $this->request->getPost('comment'),
]);
}
}
Three changes hide in there. $this->input->post('x') becomes $this->request->getPost('x'), part of a real request object with getGet(), getVar() and getMethod(). show_404() becomes a thrown exception. And the view is returned, not echoed - CI4 controllers return a response, which is what makes redirects and JSON replies composable instead of a race against output buffering.
Routing: the part that breaks the most URLs
CI3 routed automatically. A request for /blog/post/12 found Blog, called post(), passed 12. You could add entries to routes.php, but you rarely had to, and on an old app most URLs exist only because the auto-router made them exist.
CI4 has auto-routing too, disabled by default and not something to switch on for a migration. Routes are declared in app/Config/Routes.php, and this is the single biggest source of post-launch 404s, because nobody has a list of the URLs the old app actually served - the list was implicit in the class names. Build it from the access log rather than from the code, and treat every indexed URL as a contract:
// app/Config/Routes.php
$routes->get('/', 'Home::index');
// The CI3 auto-route /blog/post/12 becomes explicit:
$routes->get('blog/post/(:num)', 'Blog::post/$1');
// Grouped, with a filter, which CI3 had no first-class equivalent for.
$routes->group('account', ['filter' => 'auth'], static function ($routes) {
$routes->get('/', 'Account::index');
$routes->get('invoices/(:num)', 'Account::invoice/$1');
$routes->post('profile', 'Account::saveProfile');
});
// A URL that moved: keep the indexed one alive with a 301.
$routes->addRedirect('blog/post/(:num)', 'articles/$1');
CI4 routes are also verb-specific. A CI3 method that handled both the form display and the submission becomes a get and a post route, and forgetting the post one produces a 404 that appears only when somebody submits.
Writing hundreds of these by hand is tedious and error-prone, so we generate the first draft from the log. CI3 auto-routing has a mechanical shape - /controller/method/arg1/arg2 - which means the only real guess is whether a segment is numeric:
<?php
/**
* ci3-routes.php -- turn a list of live CI3 URLs into explicit CI4 route lines.
*
* Feed it the unique URL column of an access log. CI3 auto-routing maps
* /controller/method/arg1/arg2 , so every segment after the method is an
* argument: the only guess made here is :num versus :segment.
*/
function placeholder( $segment ) {
return ctype_digit( $segment ) ? '(:num)' : '(:segment)';
}
function ci4_route( $path, $default_controller = 'Home' ) {
$parts = array_values( array_filter( explode( '/', trim( $path, '/' ) ), 'strlen' ) );
if ( ! $parts ) {
return array( '/', $default_controller . '::index' );
}
$controller = ucfirst( array_shift( $parts ) );
$method = 'index';
// CI3 treats the second segment as the method unless it is numeric.
if ( $parts && ! ctype_digit( $parts[0] ) ) {
$method = array_shift( $parts );
}
$uri = array( strtolower( $controller ) );
$args = array();
if ( 'index' !== $method ) {
$uri[] = $method;
}
foreach ( $parts as $i => $part ) {
$uri[] = placeholder( $part );
$args[] = '$' . ( $i + 1 );
}
$handler = $controller . '::' . $method . ( $args ? '/' . implode( '/', $args ) : '' );
return array( implode( '/', $uri ), $handler );
}
$paths = array(
'/',
'/about',
'/blog/post/12',
'/blog/category/news/3',
'/invoices/download/2026-03-14',
'/admin/reports/monthly/2026/03',
);
$seen = array();
echo "// generated from the CI3 access log -- review every line\n";
foreach ( $paths as $path ) {
list( $uri, $handler ) = ci4_route( $path );
if ( isset( $seen[ $uri ] ) ) {
continue; // /blog/post/12 and /blog/post/13 collapse to one route
}
$seen[ $uri ] = true;
printf( "\$routes->get('%s', '%s');%s", $uri, $handler, PHP_EOL );
}
$ php ci3-routes.php
// generated from the CI3 access log -- review every line
$routes->get('/', 'Home::index');
$routes->get('about', 'About::index');
$routes->get('blog/post/(:num)', 'Blog::post/$1');
$routes->get('blog/category/(:segment)/(:num)', 'Blog::category/$1/$2');
$routes->get('invoices/download/(:segment)', 'Invoices::download/$1');
$routes->get('admin/reports/(:segment)/(:num)/(:num)', 'Admin::reports/$1/$2/$3');
It is a first draft, not an answer - the comment it writes into its own output says so. It cannot know that /invoices/download/2026-03-14 takes a date rather than a slug, and it will happily collapse two different routes that look alike. But it turns a week of transcription into an afternoon of review.
Database: familiar, but every call site changes
The query builder survives in spirit. The syntax is close enough to lull you and different enough to break silently.
// CI3
$this->db->select('id, title, published_at');
$this->db->from('posts');
$this->db->where('status', 'published');
$this->db->where('published_at <=', date('Y-m-d H:i:s'));
$this->db->order_by('published_at', 'DESC');
$this->db->limit(10);
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
echo $row->title;
}
}
$this->db->insert('posts', array('title' => 'Hello'));
$new_id = $this->db->insert_id();
// CI4
$db = \Config\Database::connect();
$query = $db->table('posts')
->select('id, title, published_at')
->where('status', 'published')
->where('published_at <=', date('Y-m-d H:i:s'))
->orderBy('published_at', 'DESC')
->limit(10)
->get();
if ($query->getNumRows() > 0) {
foreach ($query->getResult() as $row) {
echo esc($row->title);
}
}
$db->table('posts')->insert(['title' => 'Hello']);
$new_id = $db->insertID();
The pattern is mechanical: snake_case becomes camelCase, the table is named up front, the connection is explicit. result() becomes getResult(), num_rows() becomes getNumRows(), insert_id() becomes insertID() - note the capital D, which will cost you ten minutes at least once.
Models are the genuinely bigger change. CI3 models were plain classes with a database handle; CI4's Model brings $allowedFields, validation rules, timestamps, soft deletes and Entity classes. It is better, and it is not a search-and-replace. On a migration, extend CI4's Model with only $table, $primaryKey and $allowedFields, port the queries as-is, and adopt entities and validation later as separate work.
Config, sessions and environments
CI3 kept credentials in application/config/database.php, committed to the repository more often than anyone admits. CI4 reads a .env file at the project root, which is not committed, and keys there override the config classes:
CI_ENVIRONMENT = production
app.baseURL = 'https://example.com/'
app.indexPage = ''
database.default.hostname = localhost
database.default.database = myapp
database.default.username = myapp
database.default.password = 'set-this-outside-the-repo'
database.default.DBDriver = MySQLi
CI_ENVIRONMENT replaces CI3's ENVIRONMENT constant in index.php, and it does more: in development you get the debug toolbar and full exception pages, in production you get a generic error page. Getting this wrong in the other direction - shipping development to production - is how a migration leaks a stack trace with a database host in it on day one.
Sessions are a config class now, reached with session() rather than $this->session. Read that config carefully if you plan to run both apps side by side: a shared session means matching the handler, the cookie name and the storage on both.
The plan that keeps the business running
First, before touching CI4 at all: get CI3 running green on a modern PHP. CI3 supports PHP 8 in its later releases. Update it, fix the deprecations, run the app, and ship that. It is unglamorous and it is the highest-value step in the project, because otherwise every bug you hit afterwards has two possible causes - the framework change and the language change - and you will spend your time deciding which, instead of fixing either.
Then move in slices. Stand the CI4 app up beside the CI3 app behind the same web server, and route by URL prefix: everything under /account/ goes to CI4, everything else still goes to CI3. Move one group at a time, smallest first, deploying after each. The apps share the database, and share a session store if the login has not moved yet.
This is the strangler shape - you grow the new app around the old one until the old one has nothing left to serve - and the reason to use it here is not fashion. It is that every slice is independently revertible. If the account pages go wrong on Tuesday, you flip that prefix back to CI3 and the rest of the site never noticed. A big-bang cutover gives you one enormous, irreversible Tuesday.
Keep a route map - old URL, new URL, status - from day one. It tells you when you are finished, and it stops URLs quietly disappearing.
Proving parity
The cheapest real proof that a migration did not lose anything is a before-and-after fetch of every public URL, compared as text. This is how we check:
# urls.txt holds every public path, one per line, taken from the access log.
fetch() { # fetch <host> <outdir>
mkdir -p "$2"
while read -r path; do
name=$(printf '%s' "$path" | md5sum | cut -c1-12)
curl -sS -o "$2/$name.html" -w "%{http_code} $path\n" "$1$path"
done < urls.txt > "$2/status.txt"
}
norm() { sed -e 's/<[^>]*>/ /g' "$1" | tr -s '[:space:]' ' '; }
fetch https://legacy.example.com before
fetch https://staging.example.com after
# Status codes first: any 404 here is a route you have not ported.
diff before/status.txt after/status.txt
# Then the visible text, so markup churn does not drown the real differences.
for f in before/*.html; do
name=$(basename "$f")
diff <(norm "$f") <(norm "after/$name") > /dev/null \
&& echo "same: $name" \
|| echo "DIFFERS: $name"
done
Stripping tags is what makes this usable. Markup will change - templates get rebuilt, classes renamed - and none of that matters; what matters is whether the same words, prices and dates come out. The status diff alone catches the route gaps, before your users do.
When not to do this
If the app is small - a handful of controllers, a few dozen routes, no unusual libraries - a clean build on a current framework is often cheaper than a migration, and you get to drop the accumulated dead code instead of carrying it across. The honest test is whether you would keep the existing database schema. If the answer is no, you are rewriting anyway; call it that and plan it properly.
The other case is an app that is genuinely frozen: internal, stable, nobody asking for features. That app does not need CI4. It needs to run on a supported PHP, with backups and a patched server, and the CI3 codebase can sit exactly where it is. Migrating software that nobody is going to change is spending money to hold still.
If you have a CI3 app that has quietly become the thing nobody wants to touch, that is the CodeIgniter work we do, including the unglamorous PHP 8 step first. It overlaps with the rest of our web application work, so the plan comes with an honest opinion on whether to migrate at all. Start a project with the route list and we reply within two business days.
We ship and run our own products. We build yours the same way.
Start a project