PHP

Lesson 02

Input validation and filtering

Validate request input at the boundary before it reaches query, domain, or template code.

Good Code

public/orders.php
<?php declare(strict_types=1);

$orderId = filter_input(
    INPUT_GET,
    'order_id',
    FILTER_VALIDATE_INT,
    ['options' => ['min_range' => 1]]
);

if ($orderId === false || $orderId === null) {
    http_response_code(400);
    echo 'Invalid order id';
    return;
}

$order = $orders->findById($orderId);

Bad Code

public/orders.php
<?php

$orderId = $_GET['order_id'];

if (!$orderId) {
    echo 'Missing order id';
}

$order = $orders->findById($orderId);

Review Notes

What to review

Good Code

The good version reads the original request value, validates that it is a positive integer, and stops early with a clear HTTP response.

Bad Code

The bad version pulls directly from $_GET, treats empty and invalid values the same, and passes a raw boundary value deeper into the application.

Takeaways

  • Superglobals are untrusted boundaries; normalize them into explicit values before using them.