CodeIgniter interview questions and answers for PHP developers
CodeIgniter interview questions test whether you know how a request travels through the framework (front controller, routes, filters, controller, model, view) and whether you write it safely: validated input, Query Builder or bound queries, escaped output and CSRF protection. Many roles maintain an older CodeIgniter 3 app or are moving one to CodeIgniter 4, so expect questions on what changed between them as well as on models, migrations and tests.
By Evin JohnPublished 8 min read
Where CodeIgniter questions come up
CodeIgniter is common in agencies, internal business systems and long-running products, many of them built on CodeIgniter 3 years ago. That shapes the interview: alongside framework basics, you are often asked how you would add a feature to an app with no tests, or how you would plan a move to CodeIgniter 4. General PHP questions (types, OOP, Composer, sessions) usually come first and are covered in PHP interview questions. If the team also weighs Laravel, expect a comparison question; see Laravel interview questions. Full-stack listings often add front-end styling questions too, the kind in CSS3 interview questions.
- PHP and framework basicsShort questions on MVC, routing, the request lifecycle and the folder layout.
- Build or extend a featureA CRUD screen with validation, a model and a view, sometimes as a take-home, sometimes live with screen sharing.
- Security and dataHow you stop SQL injection, XSS and CSRF in this framework, and how you structure queries and migrations.
- Legacy and scaleA slow page, a CI3 controller with business logic everywhere, or an upgrade plan. Interviewers want a safe order of steps.
CodeIgniter fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is CodeIgniter and why would a team choose it? | Positioning | A lightweight PHP MVC framework with a small footprint, little required configuration and a gentle learning curve. Teams pick it for speed of delivery and simple hosting, and accept fewer built-in features than larger frameworks. |
| Describe the request lifecycle in CodeIgniter 4. | Lifecycle | The web server sends everything to public/index.php, the framework loads config, matches the route, runs before filters, calls the controller method, which uses models and returns a view or response, then after filters run and the response is sent. |
What lives in app/, public/, writable/ and system/? | Layout | Your code and config in app/, the web root with index.php and assets in public/, logs, cache, sessions and uploads in writable/, and the framework itself in system/ (or under vendor when installed with Composer). Only public/ should be web-accessible. |
| How do you define routes? | Routing | In app/Config/Routes.php, mapping HTTP verbs and URI patterns (with placeholders such as (:num) and (:segment)) to controller methods. Resource routes generate the standard REST set. |
| What is auto routing, and why do many teams turn it off? | Routing safety | It maps URLs to controller methods by name without a route list. It is convenient but can expose methods nobody meant to publish. Current CodeIgniter 4 versions ship with it disabled and offer an improved, stricter variant. |
| What are helpers and libraries? | Building blocks | Helpers are collections of plain functions (url, form, text) loaded when needed. Libraries are classes for larger features such as email, image handling or pagination. |
| How do you pass data to a view and print it safely? | Views | Return view('name', $data) from the controller, and in the view print with esc(), which escapes for HTML by default and has contexts for attributes, JavaScript, CSS and URLs. |
What is the .env file for? | Configuration | Environment-specific settings such as the base URL, database credentials and CI_ENVIRONMENT. It overrides config values and should never be committed with real secrets. |
What does php spark do? | CLI | Runs framework commands: the development server, migrations and seeds, generators for controllers and models, route listing and cache clearing. You can write your own commands too. |
| How is error display handled in production? | Environments | With CI_ENVIRONMENT set to production, detailed errors are hidden from users and logged instead. Leaving development mode on in production leaks stack traces and paths. |
Models, Query Builder and data questions
<?php
// app/Models/ProductModel.php
namespace App\Models;
use CodeIgniter\Model;
class ProductModel extends Model
{
protected $table = 'products';
protected $returnType = 'array';
protected $allowedFields = ['name', 'price', 'stock'];
protected $useTimestamps = true;
protected $useSoftDeletes = true;
protected $validationRules = [
'name' => 'required|max_length[120]',
'price' => 'required|decimal',
'stock' => 'required|is_natural',
];
public function lowStock(int $limit = 5): array
{
return $this->where('stock <', $limit)->orderBy('stock')->findAll();
}
}
// app/Controllers/Products.php
namespace App\Controllers;
use App\Models\ProductModel;
use CodeIgniter\Exceptions\PageNotFoundException;
class Products extends BaseController
{
public function show(int $id)
{
$product = model(ProductModel::class)->find($id);
if ($product === null) {
throw PageNotFoundException::forPageNotFound();
}
return view('products/show', ['product' => $product]);
}
public function create()
{
$model = model(ProductModel::class);
if (! $model->insert($this->request->getPost(['name', 'price', 'stock']))) {
return redirect()->back()->withInput()->with('errors', $model->errors());
}
return redirect()->to('/products');
}
}- What does `$allowedFields` protect against? Mass assignment. Only the listed columns are written on insert or update, so a crafted form field such as
is_adminis dropped. Leaving it empty means nothing can be saved, which surprises new developers. - Model or Query Builder directly? The model adds validation, timestamps, soft deletes, callbacks and pagination on top of the Query Builder. For one-off reports or complex joins, the builder from
db_connect()is fine; keep it out of controllers anyway. - How do you prevent SQL injection? Query Builder escapes values it receives, and raw queries use bindings (
?placeholders with an array of values). Building SQL by concatenating request input is the bug interviewers are looking for. - What are model callbacks? Methods listed in properties such as
beforeInsertorafterUpdate, used for things like hashing a password before save. They are skipped by raw builder queries, which is a common source of bugs. - How do transactions work?
transStart()andtransComplete()wrap a group of queries and roll back automatically on a database error;transStatus()tells you whether it committed. Manual begin, commit and rollback are available for finer control. - What are entities? Classes representing one row with casting, mutators and business methods, returned by models configured for them. They keep domain logic out of controllers and arrays.
- How do migrations and seeds help a team? Schema changes live in versioned files run with
php spark migrate, so every environment can be rebuilt the same way. Seeds load test or reference data. Rolling back requires a correctdown()method. - How do you avoid the N+1 query problem without an ORM's eager loading? Fetch the parent rows, collect their IDs, load all children with one
whereInquery and group them in PHP, or write a join when you only need flat data.
Security, filters and sessions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What are filters in CodeIgniter 4? | Middleware | Classes with before and after methods that run around controllers, configured globally, per HTTP method or per route. Authentication checks, CSRF, CORS and response headers are typical uses. They replaced much of what hooks did in CI3. |
| How is CSRF protection enabled? | CSRF | Turn on the CSRF filter and include the token in forms with csrf_field(). AJAX requests send the token in a header or field. Token regeneration on every request can break pages with several tabs or parallel requests; know the setting. |
| How do you prevent XSS? | Output | Escape at output with esc() in the right context, validate input, and add a content security policy. Escaping on input instead corrupts data and misses other output contexts. |
| How would you add login to a CodeIgniter 4 app? | Auth | Use the official Shield library or a well-reviewed package rather than writing it from scratch, hash passwords with PHP's password_hash, regenerate the session ID on login and protect routes with a filter. |
| Which validation features do you use most? | Validation | Rule strings such as required, valid_email, is_unique[table.field] and permit_empty, custom rule classes, and placeholders for the current record so updates do not fail uniqueness against themselves. |
| Why do concurrent AJAX calls sometimes queue up? | Session locking | File-based sessions lock the session for the whole request. Closing the session early when you only read it, or choosing a driver with different locking behavior, lets requests run in parallel. |
| How do you handle file uploads safely? | Uploads | Validate size, extension and MIME type with upload rules, store files outside public/ (under writable/uploads) with a generated name, and serve them through a controller that checks permissions. |
Senior and scenario questions
- How would you migrate a CodeIgniter 3 app to CodeIgniter 4? There is no in-place upgrade, since CI4 is a rewrite with namespaces, a new folder layout and different APIs. Freeze features, add characterization tests on key pages, move config and routes first, port models and libraries, then controllers and views module by module, and run both behind the web server during the transition if needed.
- What changes most between CI3 and CI4 code?
$this->load->model()and the CI super object give way to namespaced classes,model()andservice().$this->inputbecomes the request object, form validation moves to the validation service, hooks mostly become filters, and Composer becomes standard. - A product list page takes six seconds. How do you investigate? Turn on the debug toolbar in a non-production environment to see queries and timing, look for queries inside loops, missing indexes and large result sets without pagination, then cache expensive fragments with the cache service.
- How do you test a CodeIgniter 4 app? PHPUnit with the framework's test case classes, feature tests that call routes and assert on responses, a database trait that migrates and seeds a test database, and mocked services for email or external APIs.
- What are services, and why do they matter for testing? The
Config\Servicesclass builds shared instances of core components (request, validation, cache). Tests can inject mocks into it. It behaves like a central factory rather than constructor injection; see dependency injection interview questions for the trade-off. - A controller has nine hundred lines of business logic. Where do you start? Do not rewrite it in one go. Pull pure calculations into small classes with tests, move queries into models, and leave the controller to read input and choose a response.
- How do you deploy CodeIgniter safely? Point the web root at
public/, set production in the environment, makewritable/writable but not served, run migrations as a step in the release, and clear caches after config changes. - How do you build a JSON API in CodeIgniter 4? Resource routes with a resource controller, the API response trait for consistent status codes, a filter for token checks, and validation errors returned as structured JSON with a 422 status.
Fictional example
- Interviewer
- Have you had to change a CodeIgniter app without tests? How did you keep it safe?
- Candidate
- We had a CI3 invoicing module where totals were computed inside a controller with raw SQL strings built from POST data. Finance wanted a new tax rule. Before touching it I wrote characterization tests that called the endpoint with saved real requests and compared the totals. Then I moved the calculation into its own class with unit tests, replaced the concatenated SQL with bound queries, and only then added the tax rule behind a config flag. We released it to one client first and compared invoices for a week. That module later became the first one we ported to CodeIgniter 4, because its logic was already separated.
Practice plan for a CodeIgniter interview
- Days 1 and 2: install CodeIgniter 4 with Composer, build a products CRUD with defined routes, a model with allowed fields and validation, and escaped views.
- Day 3: add a login filter, CSRF in forms and AJAX, and a file upload stored outside the web root.
- Day 4: write migrations and a seeder, then a feature test for the list and create pages against a test database.
- Day 5: read a CodeIgniter 3 controller (from an old project or tutorial) and write down how each part maps to CodeIgniter 4.
- Days 6 and 7: rehearse the slow page, legacy refactor and upgrade questions aloud, in a clear order of steps.
Legacy and upgrade questions are long answers, and it is easy to skip the step about tests when you talk fast. Natively, an AI interview assistant for Mac and Windows, transcribes your mock PHP interview on your computer, so you can check the order you actually gave. During practice it can read a controller or an error page from a screenshot and suggest what to raise, help with coding tasks, and with Pro or the free trial use the résumé and job description you add. Transcripts and notes stay available afterwards.
Questions people ask
What CodeIgniter questions are asked in interviews?
The request lifecycle and folder layout, routing and auto routing, models with allowed fields, Query Builder and bindings, validation, filters, CSRF and output escaping, migrations, testing, and how CodeIgniter 3 differs from CodeIgniter 4.
What is the difference between CodeIgniter 3 and CodeIgniter 4?
CodeIgniter 4 is a rewrite with namespaces, Composer, a public web root, filters instead of most hooks, a new validation and request API, and the spark command-line tool. There is no in-place upgrade from CodeIgniter 3.
How do you prevent SQL injection in CodeIgniter?
Use the Query Builder or models, which escape values, and use query bindings with placeholders for raw SQL. Never concatenate request input into a query string.
What are filters in CodeIgniter 4?
Classes that run before or after controllers, configured globally or per route. They handle concerns like authentication checks, CSRF protection, CORS and response headers.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
