EthicsComputerCourses
Join training +91 90532 10052

Forms, Validation & CSRF

LAMP Stack · Lesson 11 of 20 Intermediate 11 min read Updated

By the end of this lesson every form in ShikshaPortal will be checked in three places: in the browser for speed, in PHP for safety, and in MySQL as the last guard. You will build a small reusable Validator class, show the same rules as HTML attributes, list errors in an accessible summary, and add a secret token to every POST form so that other websites cannot submit forms in your staff's name.

What you should know first: Handling Forms and Form Validation & Escaping from the PHP course, the student form from CRUD with Prepared Statements, the session code from Sessions, Login & Password Hashing, and the partials/field template from PHP Templates & Layouts.

Three checks, three jobs

Think of a board exam centre in Lucknow. The invigilator at the gate glances at your admit card, which catches most mistakes quickly. The centre superintendent then checks the card against the official list, because a fake card can fool a glance. Finally, the board's own records decide whether your result counts. Each check has a different job.

WhereToolIts jobCan it be skipped?
BrowserHTML attributes such as pattern and maxlengthQuick help for honest usersYes, with curl or developer tools
PHPStudentValidatorThe real rules, with clear messagesNo, every request passes through it
MySQLUNIQUE, CHECK, foreign keysLast guard against bugs and racesNo

The middle row is the one that protects you. The first row only saves time, and the last row gives ugly errors if PHP lets bad data through.

Step 1: a small Validator class

The CRUD lesson checked each student field by hand. A second form (subjects, exams, marks) would repeat the same trimming and length checks. Create src/Validation/Validator.php, so each rule is written once:

PHP
<?php
declare(strict_types=1);

namespace Shiksha\Validation;

use DateTimeImmutable;

/** Reads untrusted form input one field at a time, cleaning values and collecting errors. */
final class Validator
{
    /** @var array<string, string> */
    private array $errors = [];

    public function __construct(private readonly array $input)
    {
    }

    /** Trimmed text of $min to $max characters, optionally matching a regular expression. */
    public function text(string $field, int $min, int $max, string $message, ?string $pattern = null): string
    {
        $raw = $this->input[$field] ?? '';
        // Collapse runs of spaces; with the u flag, invalid UTF-8 gives null and fails below
        $value = is_string($raw) ? trim(preg_replace('/\s+/u', ' ', $raw) ?? '') : '';
        $length = mb_strlen($value);

        if (!is_string($raw) || $length < $min || $length > $max
            || ($pattern !== null && !preg_match($pattern, $value))) {
            $this->fail($field, $message);
        }
        return $value;
    }

    /** A real calendar date written as YYYY-MM-DD, between $from and $to. */
    public function date(string $field, string $from, string $to, string $message): string
    {
        $value = $this->text($field, 10, 10, $message);
        $date = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
        if ($date === false || $date->format('Y-m-d') !== $value || $value < $from || $value > $to) {
            $this->fail($field, $message);
        }
        return $value;
    }

    /** A whole number that must be one of $allowed, such as a class id from a drop-down list. */
    public function oneOf(string $field, array $allowed, string $message): ?int
    {
        $raw = $this->input[$field] ?? null;
        $value = is_string($raw) ? filter_var($raw, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE) : null;
        if (!in_array($value, $allowed, true)) {
            $this->fail($field, $message);
        }
        return $value;
    }

    /** Record an error; the first message for a field wins. */
    public function fail(string $field, string $message): void
    {
        $this->errors[$field] ??= $message;
    }

    public function errors(): array
    {
        return $this->errors;
    }
}

Four details do quiet but important work:

  • is_string($raw) rejects full_name[]=x, which PHP turns into an array. The field simply fails instead of crashing with a TypeError.
  • preg_replace('/\s+/u', ' ', ...) turns "Ananya Mishra" into "Ananya Mishra". With the u flag, text that is not valid UTF-8 makes preg_replace() return null, so broken bytes can never reach the database.
  • mb_strlen() counts characters, not bytes. A Hindi name such as "अनन्या" is 6 characters but 18 bytes, and strlen() would wrongly call it long.
  • fail() is public, so rules that involve two fields, or the database, can add their own message.

The class lives under Shiksha\Validation, so Composer's PSR-4 rule from Composer & Autoloading finds it with no changes.

Step 2: the school's rules

src/Models/StudentValidator.php now reads like the school's admission rules:

PHP
private const NAME = "/^\p{L}[\p{L}\p{M} .'-]*$/u";

public static function validate(array $input, array $classIds): array
{
    [$oldest, $youngest] = self::birthRange();   // today minus 20 years, today minus 3 years
    $v = new Validator($input);

    $data = [
        'admission_no' => strtoupper($v->text('admission_no', 12, 12,
            'Use the format SP-2026-0042.', '/^SP-\d{4}-\d{4}$/i')),
        'full_name' => $v->text('full_name', 2, 100,
            'Enter the name in letters (2 to 100 characters).', self::NAME),
        'date_of_birth' => $v->date('date_of_birth', $oldest, $youngest,
            'Enter a real date for a child aged 3 to 20.'),
        'class_id' => $v->oneOf('class_id', $classIds, 'Choose a class from the list.'),
        'guardian_name' => $v->text('guardian_name', 2, 100,
            'Enter the guardian\'s name in letters.', self::NAME),
        'guardian_phone' => self::mobile($v->text('guardian_phone', 10, 16,
            'Enter a 10-digit mobile number.')),
    ];
    if (!preg_match('/^[6-9]\d{9}$/', $data['guardian_phone'])) {
        $v->fail('guardian_phone', 'Enter a 10-digit mobile number.');
    }

    return [$data, $v->errors()];
}

\p{L} means "a letter in any script" and \p{M} means "a combining mark", such as the vowel signs in Devanagari. So the pattern accepts Hindi and Urdu names, "D'Souza" and "K. Ramesh", but not < or digits. The private mobile() method removes spaces, dashes and a +91 prefix, so "+91 98390-12345" is stored as 9839012345.

Notice what is not here: status, id and photo are never read from the input. The returned $data holds exactly six keys, and only $data goes to the repository. Passing $_POST straight to an INSERT would let a visitor set any column they can guess, which is called mass assignment. We fed the class seven test inputs from a small script; each line shows the clean data or the errors:

Output
good   {"admission_no":"SP-2026-0036","full_name":"Ananya Mishra","date_of_birth":"2011-08-14","class_id":3,"guardian_name":"Rakesh D'Souza","guardian_phone":"9839012345"}
hindi  {"admission_no":"SP-2026-0036","full_name":"अनन्या मिश्रा","date_of_birth":"2011-08-14","class_id":3,"guardian_name":"Rakesh D'Souza","guardian_phone":"9839012345"}
script {"full_name":"Enter the name in letters (2 to 100 characters)."}
baby   {"date_of_birth":"Enter a real date for a child aged 3 to 20."}
array  {"full_name":"Enter the name in letters (2 to 100 characters)."}
class  {"class_id":"Choose a class from the list."}
extra  {"admission_no":"SP-2026-0036","full_name":"Ananya Mishra","date_of_birth":"2011-08-14","class_id":3,"guardian_name":"Rakesh D'Souza","guardian_phone":"9839012345"}

The "extra" input also sent status=left and id=1; both were ignored.

Step 3: the same rules in the browser

Rules written twice drift apart. So StudentValidator also returns the matching HTML attributes, from one place:

PHP
public static function htmlAttributes(): array
{
    [$oldest, $youngest] = self::birthRange();
    return [
        'admission_no' => ['maxlength' => 12, 'pattern' => '[Ss][Pp]-[0-9]{4}-[0-9]{4}', 'placeholder' => 'SP-2026-0042'],
        'full_name' => ['minlength' => 2, 'maxlength' => 100],
        'date_of_birth' => ['min' => $oldest, 'max' => $youngest],
        'guardian_name' => ['minlength' => 2, 'maxlength' => 100],
        'guardian_phone' => ['maxlength' => 16, 'inputmode' => 'tel', 'autocomplete' => 'tel'],
    ];
}

The controller passes them to the form, and partials/field.php prints each pair inside the <input> tag as <?= e($attr) ?>="<?= e($attrValue) ?>", escaped and quoted as the templates lesson taught. The browser's pattern must match the whole value, so it needs no ^ or $. This page uses the exact attributes our server sent on 16 November 2026. Press Check to see what the browser says about each field:

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Browser checks</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    label { display: block; font-weight: 600; margin-top: 8px; }
    pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }
  </style>
</head>
<body>
  <h1>Add a student</h1>
  <form id="student">
    <label for="admission_no">Admission no.</label>
    <input id="admission_no" name="admission_no" value="SP-26-36" required maxlength="12" pattern="[Ss][Pp]-[0-9]{4}-[0-9]{4}" placeholder="SP-2026-0042">
    <label for="full_name">Full name</label>
    <input id="full_name" name="full_name" value="A" required minlength="2" maxlength="100">
    <label for="date_of_birth">Date of birth</label>
    <input id="date_of_birth" name="date_of_birth" type="date" value="2025-01-10" required min="2006-11-16" max="2023-11-16">
    <label for="guardian_phone">Guardian mobile</label>
    <input id="guardian_phone" name="guardian_phone" type="tel" value="+91 98390-12345" required maxlength="16" inputmode="tel">
    <p><button type="button" id="check">Check</button></p>
  </form>
  <pre id="out"></pre>
  <script>
    document.querySelector("#check").addEventListener("click", () => {
      const lines = [];
      for (const input of document.querySelectorAll("#student input")) {
        lines.push(input.name + ": " + (input.validity.valid ? "OK" : input.validationMessage));
      }
      lines.push("", "Even when every line says OK, the server checks again.");
      document.querySelector("#out").textContent = lines.join("\n");
    });
  </script>
</body>
</html>

minlength only complains about text the user has typed, so the prefilled "A" may show OK until you edit it. That is one more reason the server must decide.

Step 4: an error summary at the top

A long form with errors near the bottom is easy to misread. templates/students/form.php now starts with a summary whose links jump to each broken field. This is the real HTML our server returned for a bad submission (the <main> part, shortened), with the stylesheet pasted in:

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Add a student | ShikshaPortal</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    label { display: block; font-weight: 600; }
    .error-summary { border: 2px solid #b00020; padding: 0 1rem; }
    .error { color: #b00020; display: block; }
  </style>
</head>
<body>
  <h1>Add a student</h1>
  <div class="error-summary" role="alert">
    <p>Please fix 3 problem(s):</p>
    <ul>
      <li><a href="#admission_no">Use the format SP-2026-0042.</a></li>
      <li><a href="#full_name">Enter the name in letters (2 to 100 characters).</a></li>
      <li><a href="#date_of_birth">Enter a real date for a child aged 3 to 20.</a></li>
    </ul>
  </div>
  <form method="post" action="/students/new">
    <input type="hidden" name="_csrf" value="835249f9f841a78a0fc0354de1dc181e71863a00f6d294ba29cbdbdb220eb7af">
    <p>
      <label for="admission_no">Admission no.</label>
      <input id="admission_no" name="admission_no" type="text" value="SP-26-36" required maxlength="12" pattern="[Ss][Pp]-[0-9]{4}-[0-9]{4}" aria-invalid="true" aria-describedby="admission_no-error">
      <strong class="error" id="admission_no-error">Use the format SP-2026-0042.</strong>
    </p>
    <p>
      <label for="full_name">Full name</label>
      <input id="full_name" name="full_name" type="text" value="&lt;b&gt;Ananya&lt;/b&gt;" required minlength="2" maxlength="100" aria-invalid="true" aria-describedby="full_name-error">
      <strong class="error" id="full_name-error">Enter the name in letters (2 to 100 characters).</strong>
    </p>
    <p>
      <label for="date_of_birth">Date of birth</label>
      <input id="date_of_birth" name="date_of_birth" type="date" value="2025-01-10" required min="2006-11-16" max="2023-11-16" aria-invalid="true" aria-describedby="date_of_birth-error">
      <strong class="error" id="date_of_birth-error">Enter a real date for a child aged 3 to 20.</strong>
    </p>
    <button>Save</button>
  </form>
</body>
</html>

role="alert" makes screen readers announce the summary as soon as the page loads. The typed <b>Ananya</b> comes back as harmless text, because the partial escapes every value. Notice the hidden _csrf field too; the rest of this lesson explains it.

What cross-site request forgery is

Imagine someone prints a letter on a copy of your school's letterhead, "Please mark student 5 as left", and slips it into the principal's tray. The tray accepts anything that looks official. CSRF (cross-site request forgery) is the web version. Neha is logged in to ShikshaPortal in one tab. In another tab she opens a page from a stranger, which contains a hidden form pointing at http://shiksha.test/student/leave?id=5 and submits it with JavaScript. Her browser attaches her session cookie, so without protection the server would obey.

Our SameSite=Lax cookie from the sessions lesson already stops modern browsers from sending the cookie with cross-site POSTs. We still add a token, for three reasons: SameSite treats every subdomain of a site as "same site", so a hacked blog.school.example could still attack portal.school.example; older browsers ignore the attribute; and security works best in layers. The fix is a secret value that the attacker's page cannot read: a CSRF token.

Step 5: one token per session

Add three small pieces to src/auth.php. start_session() creates the token, login_user() replaces it, and csrf_valid() checks it:

PHP
// at the end of start_session(): one secret token per session
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));

// in login_user(), after session_regenerate_id(true):
$_SESSION['csrf'] = bin2hex(random_bytes(32)); // and a fresh CSRF token

function csrf_token(): string
{
    return $_SESSION['csrf'] ?? '';
}

/** True when a POST request carries this session's token. */
function csrf_valid(): bool
{
    $sent = $_POST['_csrf'] ?? '';
    return is_string($sent) && csrf_token() !== '' && hash_equals(csrf_token(), $sent);
}

random_bytes(32) comes from the operating system's secure random source, giving 64 hex characters that nobody can guess. hash_equals() compares in constant time, so the response time never reveals how many characters matched. A new token at login means a token seen by anyone before login is useless afterwards.

Step 6: check every POST in one place

A check inside each controller would be forgotten in the next new form. So public/index.php checks every POST before the router runs:

PHP
// Every POST must prove it came from one of our own forms
if ($method === 'POST' && !csrf_valid()) {
    http_response_code(403);
    render('error', [
        'title' => 'Form expired',
        'message' => 'Please go back, reload the page and send the form again.',
    ]);
    exit;
}

Then every POST form gets one hidden line, filled from a csrf value the controller or render() passes in: the student form, the login form, the "Mark as left" and "Delete" buttons, and the logout button in partials/header.php.

PHP
<input type="hidden" name="_csrf" value="<?= e($csrf) ?>">

The login form needs it too. Without it, an attacker could log a victim in to the attacker's account, and anything the victim typed next would be saved there. We tested the whole flow against our Apache copy with curl:

Output
POST /login without a token                     403 Forbidden
POST /login with the token from GET /login      303 See Other, Location: /
POST /students/new with the pre-login token     403
POST /student/leave?id=5 with cookie, no token  403  <h1>Form expired</h1>
POST /logout with _csrf[]=x                     403
POST /students/new with token and good data     303 See Other, Location: /student?id=9

The fourth line is the forged-letter attack: the cookie arrived, but the token did not, so nothing changed. The third line shows the token changing at login.

Common mistakes

  • Trusting the browser's checks. pattern and required disappear with curl. The server must repeat every rule.
  • Passing $_POST to an INSERT. Build a clean array of the fields you allow.
  • strlen() on names. It counts bytes; use mb_strlen() for Indian-language text.
  • Checking CSRF in some controllers only. Check every POST centrally.
  • Putting the token in a GET link. It leaks into logs and Referer headers. Tokens belong in POST bodies.

Interview questions

1. Why validate on the server if the browser already validates?

Browser validation is a convenience that any user can switch off or bypass by sending the request directly. The server is the only place you control, so it must enforce every rule. Database constraints then act as a final safety net.

2. How does a CSRF token protect a form?

The server stores a random secret in the session and puts it in a hidden field of its own forms. A forged request from another site carries the victim's cookie but cannot read the page to learn the token, so the server rejects it. The comparison should use hash_equals().

3. If cookies are SameSite=Lax, do you still need CSRF tokens?

Lax blocks most cross-site POSTs in modern browsers, but subdomains count as the same site, older clients ignore it, and some attacks come from the same site. Tokens are cheap defence in depth, and OWASP recommends them.

4. What is mass assignment?

It is copying all request fields into a database record, so a user can set fields they should not, such as role or status. Avoid it by building the data array from an explicit list of allowed fields.

Key points

  • Check input in the browser for speed, in PHP for safety, and in MySQL as the last guard.
  • Validator handles arrays, spacing, invalid UTF-8 and character counts once, for every form.
  • StudentValidator returns exactly the allowed fields, and the matching HTML attributes from the same place.
  • An error summary with role="alert" links each message to its field.
  • One random token per session, renewed at login, sits in a hidden _csrf field in every POST form.
  • The front controller rejects any POST without a valid token, using hash_equals().

Exercise

Add an "Add exam" form at GET and POST /exams/new for admins. Rules: the name is 2 to 60 letters, digits or spaces; the academic year looks like 2026-27, and the second part must be the year after the first; the start date must fall inside that session (1 April to 31 March). Use Validator, add the hidden token, and show a summary. What status does a POST without the token get?

Show solution
PHP
public static function validateExam(array $input): array
{
    $v = new Validator($input);
    $name = $v->text('name', 2, 60, 'Use 2 to 60 letters, digits or spaces.', '/^[\p{L}\d ]+$/u');
    $year = $v->text('academic_year', 7, 7, 'Write the session like 2026-27.', '/^\d{4}-\d{2}$/');

    $from = $to = '';
    if (!isset($v->errors()['academic_year'])) {
        $start = (int) substr($year, 0, 4);
        if ((int) substr($year, 5, 2) !== ($start + 1) % 100) {
            $v->fail('academic_year', 'The second year must follow the first, like 2026-27.');
        }
        $from = "{$start}-04-01";
        $to = ($start + 1) . '-03-31';
    }
    $startsOn = $v->date('starts_on', $from, $to, 'Pick a date inside the session.');

    return [['name' => $name, 'academic_year' => $year, 'starts_on' => $startsOn], $v->errors()];
}

The controller calls require_login('admin'), then this method, and either inserts and redirects with 303 or re-shows the form with status 422. The template adds <input type="hidden" name="_csrf" value="<?= e($csrf) ?>">. A POST without the token never reaches the controller: the front controller answers 403 "Form expired".

Quick Quiz

1. Why does Validator::text() call is_string() first?

2. Where should the CSRF check happen in ShikshaPortal?

3. Which comparison should check a submitted CSRF token?

4. A visitor sends status=left along with a new student's fields. What happens?

Learn LAMP Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call