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.
Lesson 02
Validate request input at the boundary before it reaches query, domain, or template code.
<?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);<?php
$orderId = $_GET['order_id'];
if (!$orderId) {
echo 'Missing order id';
}
$order = $orders->findById($orderId);The good version reads the original request value, validates that it is a positive integer, and stops early with a clear HTTP response.
The bad version pulls directly from $_GET, treats empty and invalid values the same, and passes a raw boundary value deeper into the application.