agyanadda@gmail.com

CodeIgniter 4 Request and Response

Forms, Sessions and Security 1 min read Updated Dec 3, 2026 Topic 17 of 30

Inside a controller, $this->request is the incoming request and $this->response is what you send back.

Reading input

  • $this->request->getPost('name') — a form field
  • $this->request->getPost(['name', 'email']) — several fields as an array
  • $this->request->getGet('page') — query string (?page=2)
  • $this->request->getVar('q') — from GET or POST
  • $this->request->getJSON(true) — JSON body as an array
  • $this->request->getFile('photo') — an uploaded file
  • $this->request->getMethod(), getIPAddress(), isAJAX()

Input is returned raw. Validate it, and escape it with esc() when you print it.

Kinds of responses

  • return view('home', $data);
  • return redirect()->to('posts');, redirect()->back(), redirect()->route('posts')
  • return $this->response->setJSON($data);
  • return $this->response->setStatusCode(201)->setJSON($data);
  • return $this->response->download($path, null);

404 page

throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();

Example

Example — Contact form handler with JSON for AJAX PHP
<?php
public function send()
{
    $data = $this->request->getPost(['name', 'email', 'message']);

    if (! $this->validateData($data, [
        'name'    => 'required|max_length[100]',
        'email'   => 'required|valid_email',
        'message' => 'required|min_length[10]',
    ])) {
        if ($this->request->isAJAX()) {
            return $this->response->setStatusCode(422)->setJSON(['errors' => $this->validator->getErrors()]);
        }
        return redirect()->back()->withInput();
    }

    model('ContactModel')->insert($data);

    return $this->request->isAJAX()
        ? $this->response->setJSON(['ok' => true])
        : redirect()->to('contact')->with('success', 'Thank you! We will reply soon.');
}

A normal form post redirects with a success message. An AJAX post gets {"ok":true}, or status 422 with {"errors":{...}} when validation fails.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method reads a POST form field?

Exercise 2 True / False

$this->request->getPost() automatically makes input safe to print in HTML.

Exercise 3 Fill in the Blank

Return JSON with $this->response->___($data)

Frequently Asked Questions

In CodeIgniter 4 the Input class was replaced by the Request object. Use $this->request->getPost('field'), getGet() and getVar() instead.