CodeIgniter interview questions and answers for CodeIgniter 4
Thirty-six CodeIgniter interview questions answered for CodeIgniter 4.7: routing, filters, events, services, helpers, CSRF, XSS, sessions, Spark and what changed from version 3.
Updated 16 min read

In this article
CodeIgniter interviews today are about CodeIgniter 4: namespaced controllers, explicit routes, filters, services, the Spark CLI and the security defaults you must switch on yourself. Many question lists still describe CodeIgniter 3, with $this->load, hooks and xss_clean(). Knowing which of those answers changed is itself a strong signal in an interview.
Updated for CodeIgniter 4.7 (4.7.5, released 9 October 2026), which requires PHP 8.2 or newer. Below are the questions from the classic CodeIgniter list that still matter, rewritten for version 4, plus the topics interviewers now add. Models, entities and the Query Builder have their own article, CodeIgniter 4 model and Query Builder interview questions, so they are only touched on here.
Tested with: CodeIgniter 4.7.5 (appstarter), PHP 8.5.7, php spark serve on a local port. Route output and the escaping example below come from that run.
Basics and architecture
1. What is CodeIgniter?
CodeIgniter is a free, MIT-licensed PHP framework known for a small footprint, little required configuration and good documentation. EllisLab released it in 2006; the British Columbia Institute of Technology took it over in 2014, and the CodeIgniter Foundation maintains it now. CodeIgniter 4, a ground-up rewrite with namespaces, Composer and PHP 8 features, was released in February 2020. The latest 3.x release is 3.1.13 from 2022; new work should use version 4, and our CodeIgniter 3 to 4 migration guide explains why the move is a rewrite of the application layer rather than an upgrade.
2. What are CodeIgniter's key features?
- A small, fast core with few required conventions.
- MVC with optional models: you can call the Query Builder from a controller when a model adds nothing.
- Explicit routing, controller filters (middleware), and since 4.7, routes and filters declared with PHP attributes on controllers.
- A services layer for shared objects, Spark CLI commands, migrations and seeders.
- Built-in validation, sessions, caching, email, image manipulation, CSRF protection, a Content Security Policy builder and a debug toolbar.
- Official add-ons: Shield for authentication and Settings for stored configuration.
- Since 4.7, an optional Worker Mode that keeps the application in memory between requests.
The old claim that CodeIgniter is "2 MB" referred to version 3. Version 4 is installed through Composer and is larger, but still light compared with Laravel or Symfony.
3. Explain the architecture of a CodeIgniter 4 application.
Every request enters through public/index.php, which boots the framework and loads configuration from app/Config and the .env file. The router matches the URI to a controller method; filters run before and after the controller; the controller uses models, libraries and services, then returns a view, a JSON response or a redirect. The app/ folder holds your code (Controllers, Models, Views, Filters, Config), system/ lives in vendor/codeigniter4/framework, and writable/ holds logs, cache, sessions and uploads. Only public/ should be the web root.

4. What is MVC in CodeIgniter, and why is it called "loosely" MVC?
Models handle data, views handle presentation, controllers connect them. CodeIgniter is called loosely MVC because models are optional: a controller can use the database layer directly, and nothing forces a view for API responses. That flexibility helps small projects. On larger ones, agree a rule early, such as "all SQL lives in models or repositories", or business logic leaks into controllers.
5. What is a model, and how do you load one?
A model extends CodeIgniter\Model, names a table, and gets CRUD methods, validation, callbacks, soft deletes and pagination. In version 4 there is no $this->load->model(); you create the class, preferably through the model() helper so you get a shared instance:
use App\Models\ProductModel;
$products = model(ProductModel::class); // shared instance
$product = $products->find($id);
$fresh = new ProductModel(); // separate instance when you need oneModel configuration, $allowedFields, casting and Query Builder questions are covered in our model and Query Builder interview questions.
6. What are views, and how do you pass data to them?
Views are PHP templates in app/Views. Render one with return view('products/show', ['product' => $product]);. Keys in the array become variables in the view. Views do not escape automatically, so wrap output in esc(). Version 4 also has view layouts ($this->extend(), $this->section()), view cells for reusable widgets, and an optional parser for simple placeholders.
Controllers and routing
7. What is the default controller?
Home, with method index. Since 4.4 both are set in app/Config/Routing.php ($defaultController and $defaultMethod). The default controller is what runs for /; with explicit routes, the starter app maps $routes->get('/', 'Home::index') in app/Config/Routes.php.
8. How do you use a constructor in a controller?
Controllers extend BaseController. You can define __construct(), but the request, response and logger are not available yet. Put set-up code that needs them in initController(), and call parent::initController() first. In CodeIgniter 3 you had to call parent::__construct(); that is no longer the pattern. Better still, keep constructors light and resolve dependencies through services.
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger): void
{
parent::initController($request, $response, $logger);
$this->products = model(ProductModel::class);
}9. What is the basic URL structure?
With auto-routing the pattern is example.com/controller/method/param. In CodeIgniter 4 auto-routing is off by default ($autoRoute = false), and you define routes explicitly in app/Config/Routes.php. If you turn auto-routing on, use the "Improved" router ($autoRoutesImproved in app/Config/Feature.php, true by default), which only reaches methods prefixed with the HTTP verb, such as getShow(). URLs include index.php unless you set $indexPage = '' in app/Config/App.php and configure URL rewriting; in our test, anchor() produced /index.php/products/42 until we did.
10. What is routing, and how do you define routes?
Routing maps URIs to controller methods. Use HTTP-verb methods, placeholders, groups and names:
// app/Config/Routes.php
$routes->get('products/(:num)', 'Products::show/$1', ['as' => 'product']);
$routes->group('admin', ['filter' => 'session'], static function ($routes) {
$routes->resource('orders'); // RESTful routes for Admin orders
});Placeholders include (:num), (:segment), (:alpha), (:any) and custom ones. Generate URLs with url_to('product', 42) so a route change does not break links. Run php spark routes to see every route with its filters; it is the fastest way to debug a 404.
11. What does remapping method calls mean?
If a controller defines _remap(), CodeIgniter calls it for every request to that controller instead of the method in the URL, passing the method name and parameters. You can use it to map friendly names, add a shared check, or return a 404 for unknown methods. It still works in version 4, but route definitions are usually clearer.
public function _remap(string $method, ...$params)
{
if (method_exists($this, $method)) {
return $this->{$method}(...$params);
}
throw PageNotFoundException::forPageNotFound();
}12. What are filters?
Filters are CodeIgniter's middleware: classes implementing FilterInterface with before() and after() methods. A before() that returns a response stops the request, which is how login checks and rate limits work. You register aliases in app/Config/Filters.php and apply them globally, by HTTP method, by URI pattern or on routes. Built-in filters include csrf, cors, honeypot, invalidchars, secureheaders, forcehttps and pagecache. Filter order and arguments are a common follow-up; our filters article covers them.
13. What are hooks in CodeIgniter, and what replaced them?
CodeIgniter 3 hooks let you run code at fixed points such as pre_system or post_controller, configured in config/hooks.php. Version 4 replaces them with the Events system: you subscribe with Events::on() in app/Config/Events.php. For per-request logic around controllers, filters are usually the better tool.
14. Which event points are available?
The CodeIgniter 4 user guide lists these:
| Event | When it fires |
|---|---|
pre_system | Early, after the request and response exist, before page cache, routing and "before" filters |
post_controller_constructor | After the controller is created, before its method runs |
post_system | Just before the final output is sent, after "after" filters |
pre_command / post_command | Around a Spark command |
email | After the Email class sends a message |
DBQuery | After every database query, successful or not |
migrate | After a successful latest() or regress() migration |
You can also trigger your own events with Events::trigger('order.paid', $order).
Helpers, libraries and services
15. What is a helper, and how do you load one?
A helper is a file of plain procedural functions grouped by purpose: url, form, html, text, array, cookie, date, filesystem, inflector, number, security and xml. Load one with helper('form') or several with helper(['form', 'url']). To load helpers for all methods of a controller, list them in its protected $helpers property; to load them everywhere, add them to $helpers in app/Config/Autoload.php.
16. What is a library, and how do you load one?
A library is a class that provides a feature, such as Email, Encryption, Image, Pagination or Throttler. CodeIgniter 3 loaded them with $this->load->library(). In version 4 you get framework libraries through services, for example service('email') or \Config\Services::email(), and your own libraries are ordinary namespaced classes in app/Libraries that you instantiate or register as services.
17. What is the difference between a helper and a library?
Helpers are stateless functions for small, repeated tasks, such as building a URL or formatting a number. Libraries are classes with state and configuration, such as a mailer that holds recipients and transport settings. If you need configuration, dependencies or a test double, write a class; if you need a one-line formatting function used in views, a helper is fine.
18. What are services, and why do they matter?
Services are CodeIgniter 4's lightweight dependency injection. Each service is a static method on Config\Services that builds a configured object and, by default, returns a shared instance. You can override any framework service, for example to swap the email transport, and in tests you can inject a mock with Services::injectMock(). Interviewers like candidates who say that services make classes replaceable without editing the framework.
19. What happened to "drivers"?
CodeIgniter 3 had a driver concept: a parent library with swappable child classes, used by Cache and Session. Version 4 drops the term and uses handlers behind an interface instead. Sessions have FileHandler, DatabaseHandler, RedisHandler, MemcachedHandler and ArrayHandler (for tests); the cache has FileHandler, RedisHandler, PredisHandler, MemcachedHandler, ApcuHandler, WincacheHandler and a DummyHandler. If an interviewer asks about drivers, explain the handler pattern.
20. How do you extend a core class?
In version 3 you created MY_ prefixed classes. In version 4 you extend the framework class in your own namespace and return your class from the matching service, or, for classes without a service, configure it where the framework creates it. For controllers, put shared logic in BaseController. Avoid editing anything in vendor/: it is replaced on every update.
21. What can be autoloaded?
app/Config/Autoload.php has four settings: $psr4 (namespace to directory map), $classmap, $files (files to include on every request) and $helpers. Composer's autoloader is used as well. Libraries, models and configuration are not autoloaded in the CodeIgniter 3 sense; they are created on demand through services, model() and config().
22. How do you link to images or other assets from a view?
Put files under public/ and build URLs with the URL helper: base_url('images/logo.png'). The HTML helper's img() builds the whole tag: img(['src' => 'images/logo.png', 'alt' => 'Company logo']). Always pass alt text.
23. What does anchor() do?
anchor(), from the URL helper, creates a link: anchor('products/42', 'View product', ['class' => 'btn']). It builds the full site URL from the given URI using your base URL configuration and escapes the title. Related helpers are anchor_popup(), mailto() and safe_mailto().
Security
24. What is a CSRF token, and how do you enable CSRF protection?
A CSRF token is a random value that a form or AJAX request must send back, proving the request came from your site rather than a third-party page. In CodeIgniter 4 protection comes from the csrf filter, and it is not enabled by default: in the 4.7 starter app the line is commented out in $globals['before'] of app/Config/Filters.php. Enable it, then add <?= csrf_field() ?> to forms (the form helper's form_open() adds it automatically). Settings live in app/Config/Security.php; $csrfProtection is 'cookie' by default and can be 'session', and $regenerate controls whether the token changes on every submission. For JavaScript, send the token in the X-CSRF-TOKEN header with values from csrf_token() and csrf_hash().
25. How do you prevent XSS in CodeIgniter 4?
By escaping output for its context with esc(): esc($value) for HTML, esc($value, 'attr'), 'js', 'css' or 'url' for other contexts. In our test, a name query string containing a script tag rendered as <script>alert(1)</script>. CodeIgniter 3's xss_clean() and global XSS filtering on input were removed in version 4, because filtering input is unreliable: the same value may be safe in one context and dangerous in another. Add a Content Security Policy (app/Config/ContentSecurityPolicy.php) as a second layer.
26. How do you handle errors?
CodeIgniter 4 uses exceptions. Throw PageNotFoundException::forPageNotFound() for a 404; other exceptions become error pages from app/Views/errors. Detailed errors are shown in the development and testing environments and a generic page in production; the environment comes from CI_ENVIRONMENT. app/Config/Exceptions.php controls logging and ignored status codes, and since 4.4 you can supply your own exception handler. Write to the log with log_message('error', 'Payment failed for order {id}', ['id' => $id]); levels follow PSR-3, from emergency to debug. CodeIgniter 3's show_error() and show_404() belong to the old version, and the "inhibitor" mentioned in some lists is not a CodeIgniter component at all.
27. How do sessions work?
Get the session with session() and use set(), get(), has() and remove(). Flashdata (setFlashdata()) lasts for the next request only, and tempdata expires after a number of seconds. Configure the handler, cookie name, lifetime and ID regeneration in app/Config/Session.php. Call session()->regenerate() after login to prevent session fixation. If you use the file handler on several servers behind a load balancer, sessions will not be shared; use the database or Redis handler.
session()->set('cart_id', $cartId);
$cartId = session()->get('cart_id');
session()->setFlashdata('notice', 'Order placed');
session()->remove('cart_id');28. How do you authenticate users?
Use CodeIgniter Shield, the official authentication library. It provides session login, personal access tokens, HMAC tokens, JWT, groups and permissions, and filters such as session, tokens and permission. Writing your own login code is rarely the right answer in an interview. See protecting a CodeIgniter 4 API with Shield access tokens.
Database, CLI and email
29. Which databases does CodeIgniter support?
CodeIgniter 4 ships drivers for MySQL and MariaDB (MySQLi), PostgreSQL (Postgre), SQLite (SQLite3), Microsoft SQL Server (SQLSRV) and Oracle (OCI8). Connections are set in app/Config/Database.php or, better, in .env with keys such as database.default.hostname. Use migrations (php spark migrate) for schema changes and seeders for test data.
30. What is the CLI, and what is Spark?
Spark is CodeIgniter 4's command-line tool. Common commands are php spark serve (development server), routes, migrate, db:seed, cache:clear, make:controller, make:model, make:migration and make:filter. You can write your own commands by extending BaseCommand, which is the right home for cron jobs and queue workers. php spark optimize caches configuration and file locations for production.
31. How do you send email?
Configure the protocol (mail, sendmail or smtp) in app/Config/Email.php or .env, then use the email service:
$email = service('email');
$email->setFrom('orders@example.com', 'Example Shop');
$email->setTo($customer->email);
$email->setSubject('Your order ' . $order->number);
$email->setMessage(view('emails/order', ['order' => $order]));
if (! $email->send(false)) {
log_message('error', $email->printDebugger(['headers']));
}Passing false to send() keeps the data so printDebugger() can show it. In production, send from a Spark command or queue rather than during the web request.
32. What are the advantages and drawbacks of CodeIgniter?
Advantages: quick to learn, fast, few required conventions, good documentation, simple deployment, and an easy path for teams coming from plain PHP. Drawbacks: a smaller package ecosystem than Laravel or Symfony; no full ORM with relationships, so you write joins or batch loads yourself; and some features you take for granted elsewhere, such as queues, need a library or your own code. It suits small and medium applications, APIs and teams that want to stay close to SQL.
Questions interviewers now add
33. How does validation work?
Use $this->validate($rules) in a controller, or validateData($data, $rules) for arrays such as JSON input, then read clean values with $this->validator->getValidated(). Models can validate before insert and update with $validationRules. Rule groups live in app/Config/Validation.php. Our article on CodeIgniter 4 validation problems lists the common mistakes, such as validating the wrong request body.
34. What changed in CodeIgniter 4.7?
4.7.0 (1 February 2026) added an optional Worker Mode for persistent application servers, controller attributes for declaring routes and filters, and API transformers for shaping JSON responses, and raised the minimum PHP version to 8.2. It also included breaking changes in validation placeholders, model primary key validation and entity change detection. The 4.7.5 security release followed on 9 October 2026. See what is new in CodeIgniter 4.7 and the 4.7.5 security release guide.
Patch releases like 4.7.5 are where many teams fall behind: applying them means updating Composer, reading the change log and re-running tests on every app. If that work keeps slipping, Cloudsoft Zone's application maintenance and support service can take it on.
35. How do you test a CodeIgniter application?
With PHPUnit and CodeIgniter's test traits. FeatureTestTrait calls routes and asserts on status, JSON and redirects; DatabaseTestTrait runs migrations and seeds against a test database; ControllerTestTrait runs a controller method directly. Services can be mocked with Services::injectMock(). Our feature and database testing guide shows a full set-up.
36. What do you check before deploying to production?
Set CI_ENVIRONMENT = production, point the web server at public/, make writable/ writable but not web-accessible, enable the csrf and secureheaders filters, set a strong encryption key (php spark key:generate), use HTTPS with forcehttps, run composer install --no-dev and php spark optimize, and run migrations. The CodeIgniter 4 production checklist has the full list.
How to prepare
Create an app with composer create-project codeigniter4/appstarter and build a small feature end to end: an explicit route, a filter that checks login, a model with validation, a view that escapes output, a Spark command, and a feature test. Then switch on the CSRF filter and see what breaks, and run php spark routes to read the result. Being able to describe what you saw is worth more than memorised definitions. For the PHP side of the interview, use our PHP interview questions for 2026; for REST work, building a JSON REST API with CodeIgniter 4.7 is good practice.
Running CodeIgniter applications that need regular patching, PHP upgrades and monitoring? Cloudsoft Zone provides application maintenance and support, keeping framework releases, dependencies and servers current with tested updates.
Frequently asked questions
Should I prepare for CodeIgniter 3 or CodeIgniter 4?
CodeIgniter 4. The latest 3.x release is 3.1.13 from 2022, and new projects use version 4 (4.7.5 in October 2026). If the job maintains a CodeIgniter 3 app, also be ready to explain how you would move it to version 4.
Is CSRF protection on by default in CodeIgniter 4?
No. The
csrffilter exists but is commented out in$globalsinapp/Config/Filters.phpof the 4.7 starter app. You need to enable it and addcsrf_field()to forms.Does CodeIgniter 4 still have xss_clean()?
No. Version 4 removed input XSS filtering. Escape output with
esc()for the right context and add a Content Security Policy.What replaced hooks in CodeIgniter 4?
The Events system (
Events::on()inapp/Config/Events.php) for system points such aspre_system, and filters for logic that runs before or after controllers.
Your next customer could start right here.
Introduce your tool, product or business to readers exploring technology.
Explore placements and request a private quote
Sources
- CodeIgniter 4 User Guide: Events — CodeIgniter Foundation
- CodeIgniter 4 User Guide: Error Handling — CodeIgniter Foundation
- CodeIgniter 4 User Guide: URI Routing — CodeIgniter Foundation
- CodeIgniter 4 User Guide: Security (CSRF) — CodeIgniter Foundation
- CodeIgniter 4 User Guide: Controller Filters — CodeIgniter Foundation
- CodeIgniter 4 User Guide: Services — CodeIgniter Foundation
- CodeIgniter4 releases (v4.7.5) — GitHub, 2026-10-09
Written with substantial AI assistance. Facts checked against cited sources. Editorial policy.
Comments
No comments yet. Be the first to join the conversation.
Leave a comment
Every comment is read by a moderator before it appears. Your email address is never published; it is used only to contact you about this comment.
More from Cloudsoft Zone

Interview preparationInterview questions
PHP interview questions and answers for 2026 (PHP 8.4 and 8.5)
22 PHP interview questions grouped by level, with concise model answers and short examples covering strict types, enums, match, PDO, password hashing, property hooks and the PHP 8.5 pipe operator.
By Cloudsoft Zone

Interview preparationInterview questions
Docker interview questions and answers for Docker Engine 29
18 Docker interview questions from images and volumes to build cache, Compose, networking, signals and the containerd image store, with short model answers.
By Cloudsoft Zone

Industry updateCodeIgniter
CodeIgniter 4.7.5 security release: what to patch and how
CodeIgniter 4.7.5 fixes six advisories, including a critical upload bypass and Parser code execution. See who is exposed and how to upgrade safely.
By Cloudsoft Zone
