
PHP Patterns You Will Use in Everyday Backend Work
A practical guide to typed functions, safe input, exceptions, PDO, and JSON responses.
Typed functions
<?php
declare(strict_types=1);
function formatPrice(int|float $amount, string $currency = 'USD'): string
{
return sprintf('%s %.2f', $currency, $amount);
}
Safe input
<?php
$name = $_GET['name'] ?? 'Guest';
$page = max(1, (int) ($_GET['page'] ?? 1));
echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
PDO prepared statements
<?php
$statement = $pdo->prepare(
'SELECT id, email FROM users WHERE email = :email LIMIT 1'
);
$statement->execute(['email' => $email]);
$user = $statement->fetch();
JSON responses
<?php
function jsonResponse(array $payload, int $status = 200): never
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($payload, JSON_THROW_ON_ERROR);
exit;
}
Keep secrets outside source control, validate input at the boundary, and escape output for its destination.