CI CodeIgniter Framework

Learn CodeIgniter routing, controllers, views, models, validation, filters, migrations, APIs, and deployment.

Lessons

Sign in to save progress
1 CodeIgniter Tutorial 2 CodeIgniter HOME 3 CodeIgniter Introduction 4 CodeIgniter MVC 5 CodeIgniter Installation 6 Composer with CodeIgniter 7 CodeIgniter Spark 8 CodeIgniter Project Structure 9 public/index.php 10 CodeIgniter .env Configuration 11 App Configuration 12 Base URL 13 CodeIgniter Environments 14 Request Lifecycle 15 Namespaces & Autoloading 16 CodeIgniter Modules 17 Routing Basics 18 Route Methods 19 Route Placeholders 20 Route Filters 21 Route Groups 22 Named Routes 23 Route Priority 24 Reverse Routing 25 Controllers 26 BaseController 27 Controller Methods 28 Request Object 29 Response Object 30 Redirects 31 Content Negotiation 32 HTTP Status Codes 33 CSRF Protection 34 Views Basics 35 Layouts & Sections 36 View Cells 37 View Data 38 View Renderer 39 Escaping Output 40 HTML Forms 41 Validation Basics 42 Validation Rules 43 Custom Validation Rules 44 Validation Errors 45 Form Helper 46 Old Input 47 File Upload 48 File Validation 49 Image Manipulation 50 Email Service 51 Sessions 52 Flashdata 53 Cookies 54 Filters 55 Auth Filter 56 Throttling Filter 57 Security Headers 58 Models Basics 59 Model Configuration 60 Allowed Fields 61 Entities 62 Entity Casting 63 Model Callbacks 64 Query Builder 65 Select, Where & Order 66 Inserts & Updates 67 Deletes & Soft Deletes 68 Joins 69 Transactions 70 Pagination 71 Database Configuration 72 Migrations 73 Migration Fields 74 Foreign Keys & Indexes 75 Seeders 76 Database Forge 77 Raw Queries 78 Prepared Queries 79 Multiple Databases 80 Cache 81 Services 82 Custom Services 83 Helpers 84 Libraries 85 Config Classes 86 Events 87 CLI Commands 88 Localization 89 Language Files 90 Validation Localization 91 REST APIs 92 ResourceController 93 ResponseTrait 94 JSON Responses 95 API Validation 96 API Auth Tokens 97 CORS 98 API Rate Limits 99 API Content Negotiation 100 Testing Basics 101 Feature Tests 102 Database Tests 103 Controller Tests 104 Mock Services 105 Debug Toolbar 106 Logs 107 Error Handling 108 Exceptions 109 Performance & Caching 110 Query Optimization 111 Production Environment 112 Deployment 113 Shared Hosting 114 Nginx & Apache 115 Writable Permissions 116 Backup & Restore 117 Security Checklist 118 Code Style 119 Modules Architecture 120 Repositories & Services 121 Practical CRUD Project 122 Admin Dashboard Project 123 Auth Login Project 124 File Upload Project 125 API Project 126 CodeIgniter Examples 127 CodeIgniter Quiz 128 CodeIgniter Exercises 129 CodeIgniter Practice Problems 130 CodeIgniter Syllabus 131 CodeIgniter Study Plan 132 CodeIgniter Bootcamp 133 CodeIgniter Interview Prep 134 CodeIgniter Certificate

Logs

CodeIgniter Framework Lesson 106 of 134 ~11 min read

Overview

Read writable/logs and write useful log messages.

Logs is part of CodeIgniter's PHP framework workflow. CodeIgniter keeps the request lifecycle lightweight and clear with routes, controllers, models, views, services, filters, validation, migrations, and configuration you can understand quickly.

Core Ideas

  • Use Logs to understand CodeIgniter's route, controller, model, view, filter, and service flow.
  • Prefer simple framework features before adding heavy abstractions.
  • Validate request data, escape output, and keep database writes behind models or services.
  • Use Spark, migrations, seeders, logs, and environment files to keep projects repeatable.

Step by Step

  1. Start Logs by identifying the route and controller method.
  2. Read request data through CodeIgniter request helpers and validate it early.
  3. Use models, entities, query builder, services, or helpers for reusable work.
  4. Return a view, redirect, JSON response, or error response with clear intent.

Beginner Explanation

Logs helps you find bugs and trust changes.

Tests, logs, debug toolbar output, error handling, mocks, and code style make CodeIgniter projects easier to maintain.

Beginners should check writable/logs first when a page fails.

Before You Start

  • Before practicing Logs, run php spark routes or php spark --version so you know the app is booting.
  • Confirm .env has the correct CI_ENVIRONMENT, app.baseURL, database, and security values.
  • Check writable/logs when a page or command fails.
  • Use migrations and seeders for practice data instead of changing production tables by hand.
  • Keep one small feature goal in mind: route, controller, validation, model or service, response, and test idea.

Key CodeIgniter Concepts

  • writable/logs stores runtime logs.
  • Debug toolbar is for development only.
  • Feature tests can call routes and inspect responses.
  • Database tests should use test data and cleanup strategies.

Plain-English Glossary

  • Route: a URL and HTTP method mapped to controller code.
  • Controller: a class that handles a request and returns a response.
  • Filter: code that runs before or after a controller.
  • View: a PHP template that renders output.
  • Model: a database-facing class with allowed fields and query helpers.
  • Migration: a repeatable database schema change.
  • Seeder: a class that inserts starter or test data.
  • Service: a shared reusable object returned by the service locator.

What You Will Learn

  • Explain where Logs belongs in the CodeIgniter request lifecycle.
  • Name the main file, folder, command, or class used for this topic.
  • Write a small CodeIgniter example that follows framework conventions.
  • Identify one validation, escaping, database, security, or deployment risk for the topic.

Where You Use This in Real Projects

You use Logs in admin panels, CMS pages, forms, APIs, uploads, dashboards, reports, login flows, imports, exports, and deployment checks.

CodeIgniter is productive because the flow stays explicit: route to controller, controller to model or service, then response through a view or JSON.

A reliable CodeIgniter workflow is: define the route, validate input, call a model or service, escape output, return a response, and check logs or tests.

CodeIgniter Safety Notes

  • Validate request data before saving or using it.
  • Escape output with esc() when rendering user-controlled content in views.
  • Use allowedFields on models to protect mass assignment.
  • Use CSRF protection, filters, password hashing, prepared query builder calls, and secure environment settings.
  • Keep writable logs, cache, uploads, and sessions out of public access.

Beginner Mental Model

Think of Logs as one part of CodeIgniter's explicit route-to-response path.

The route chooses the controller, filters can guard the request, the controller coordinates validation and models, then a view, redirect, file, or JSON response is returned.

When a controller becomes hard to read, move reusable work into models, services, helpers, libraries, or config classes.

Framework Flow

  1. A request for Logs enters CodeIgniter through public/index.php and the framework bootstrap.
  2. Routes map the URL and method to a controller method, and filters can run before or after the controller.
  3. The controller reads request data, validates it, calls models, services, helpers, or libraries, and prepares a response.
  4. CodeIgniter returns a view, redirect, JSON response, file response, or error response.

Key Files and Commands

  • app/Config/Routes.php maps URLs to controllers.
  • app/Controllers, app/Models, and app/Views hold request logic, data logic, and output templates.
  • app/Config, app/Filters, app/Database/Migrations, and app/Database/Seeds organize framework behavior and database changes.
  • writable/logs is the first place to inspect runtime errors.
  • php spark routes, migrate, db:seed, make:controller, make:model, test, and serve are daily commands.

Security and Project Notes

  • Validate all request input before saving or using it.
  • Escape output with esc() when rendering user content in views.
  • Use model allowedFields to prevent unwanted mass assignment.
  • Use filters, CSRF protection, password hashing, prepared query builder calls, and environment variables for sensitive configuration.

Code Example

public function test_lessons_page_loads(): void
{
    $result = $this->get('/lessons');

    $result->assertOK();
    $result->assertSee('Lessons');
}

Another Example

public function test_lessons_page_loads(): void
{
    $result = $this->get('/lessons');

    $result->assertOK();
    $result->assertSee('Lessons');
}

More Practice Examples

Example 1: Route to controller

$routes->get('courses', 'CourseController::index', ['as' => 'courses.index']);

public function index(): string
{
    return view('courses/index', [
        'courses' => model(CourseModel::class)->orderBy('created_at', 'DESC')->paginate(10),
    ]);
}
  • The route name keeps URL generation maintainable.
  • The controller returns one view response.
  • Pagination prevents loading every row at once.

Example 2: Validate and save

$rules = [
    'title' => 'required|min_length[3]|max_length[120]',
    'slug' => 'required|alpha_dash|max_length[160]|is_unique[lessons.slug]',
];

if (! $this->validate($rules)) {
    return redirect()->back()->withInput();
}

model(LessonModel::class)->insert($this->validator->getValidated());
  • Validation runs before database writes.
  • withInput keeps form values after an error.
  • allowedFields on the model must allow only expected columns.

Example 3: Feature test

$result = $this->post('/lessons', [
    'title' => 'CodeIgniter Practice',
    'slug' => 'codeigniter-practice',
]);

$result->assertRedirect();
$this->seeInDatabase('lessons', ['slug' => 'codeigniter-practice']);
  • The test checks the HTTP response and database effect.
  • Database assertions catch save failures.
  • A focused test makes future refactors safer.

Real-World Feature Pattern

// app/Config/Routes.php
$routes->post('lessons', 'LessonController::store', ['as' => 'lessons.store', 'filter' => 'csrf']);

// app/Controllers/LessonController.php
public function store()
{
    $rules = ['title' => 'required|min_length[3]|max_length[120]'];

    if (! $this->validate($rules)) {
        return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
    }

    $lesson = model(LessonModel::class)->insert($this->validator->getValidated());

    return redirect()->route('lessons.show', [$lesson])->with('status', 'Lesson saved.');
}
  • This Logs pattern shows the CodeIgniter habit of splitting route, filter, validation, model work, and response.
  • The controller coordinates the feature but keeps database rules in the model and route protection in filters.
  • The redirect and flash message create a clear browser workflow after a successful POST.

Example Explained

  • The Logs example follows CodeIgniter conventions so routes, controllers, models, views, config, and logs stay easy to locate.
  • The route points to a controller method that handles the request.
  • Validation and filtering happen before records are changed.
  • Models, services, helpers, or libraries do reusable data and business work.
  • The final line returns a view, redirect, JSON response, file response, or error response.

How to Read This Example

  1. Start with app/Config/Routes.php so you know the URL, method, filters, and controller.
  2. Read the controller method to see request input, validation, model calls, and response type.
  3. Check model allowedFields before inserts or updates.
  4. Check views for esc() when output contains user or database values.
  5. For Logs, change one CodeIgniter layer at a time and inspect writable/logs if it fails.

Checklist

  • Use routes, controllers, models, validation, filters, migrations, and views in their intended roles.
  • Protect forms with CSRF, escape output, use allowed fields, and keep secrets in environment config.
  • Check logs, Spark commands, and debug toolbar output while developing.

Common Mistakes

  • Putting queries, validation, and HTML output into one controller method.
  • Forgetting allowedFields, validation rules, CSRF checks, escaping, or filters.
  • Editing system files instead of using app, config, services, helpers, or libraries.

Do and Don't

  • Do: practice Logs with a tiny route-to-response feature.
  • Do: use CodeIgniter conventions for routes, controllers, models, views, config, filters, and logs.
  • Do: validate input, escape output, protect allowedFields, and check writable/logs.
  • Don't: put queries, validation, and HTML output all in one controller method.
  • Don't: expose app, system, vendor, writable, .env, or logs as public web files.

Practice Challenge

Create a small CodeIgniter note, product, or lesson feature for Logs. Write the route, controller method, validation, model or migration, view or JSON response, and one debugging check.

Try These Changes

  • Add a named route and generate its URL instead of hard-coding the path.
  • Move repeated controller logic into a model, service, helper, or library.
  • Add validation and show errors with old input after a redirect.
  • Write one feature test for the success path and one validation failure.
  • For Logs, identify which CodeIgniter file owns each part of the feature.

Quick Check

  • Question: What file usually maps URLs to controllers? Answer: app/Config/Routes.php.
  • Question: Where do runtime logs live? Answer: writable/logs.
  • Question: Why use allowedFields? Answer: To prevent unsafe mass assignment.
  • Question: Why use esc() in views? Answer: To safely output user-controlled content.
  • Question: What should Logs return? Answer: A clear response such as a view, redirect, JSON response, file, or error.

Debugging Checks

  • Run php spark routes to confirm the URL, method, filters, and controller.
  • Check writable/logs for the current day log file and first useful error.
  • Confirm .env values for CI_ENVIRONMENT, app.baseURL, database, sessions, security, and logging.
  • Use debug toolbar, tests, and temporary dumps carefully in development, then remove noisy debug output.
  • For Logs, write a small feature test so the behavior can be checked again after changes.

Mini Project

Build a quality checklist for Logs: log check, debug toolbar check, feature test, database assertion, and production-safe error response.

Mastery Check

  • You can explain where Logs belongs in a CodeIgniter project and why.
  • You can connect a route, controller, validation rule, model, view, filter, and migration.
  • You can keep a CodeIgniter feature small, clear, secure, and easy to debug.
Create a free account to save which lessons you've finished. Save my progress