Lesson 5 of 7
Secure Headers & Input Hardening
Security headers instruct browsers to enforce additional protections - they're a zero-cost defense layer added with a few header() calls. Combined with rigorous input validation (no raw user data ever reaches SQL, HTML output, or file paths) they close the most common attack surfaces.
Security Headers & Input Hardening Patterns
<?php
declare(strict_types=1);
// ── Complete security headers stack ───────────────────────────
function sendSecurityHeaders(): void {
// Prevent MIME sniffing - browser uses declared Content-Type only
header("X-Content-Type-Options: nosniff");
// Prevent clickjacking - no iframing this page
header("X-Frame-Options: DENY");
// Force HTTPS - redirect HTTP to HTTPS, remember for 1 year, include subdomains
header("Strict-Transport-Security: max-age=31536000; includeSubDomains; preload");
// Control referrer information sent with outbound links
header("Referrer-Policy: strict-origin-when-cross-origin");
// Disable browser features not needed by the app
header("Permissions-Policy: camera=(), microphone=(), geolocation=()");
// CSP - restrict script/style/image sources
header("Content-Security-Policy: " . implode("; ", [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"object-src 'none'",
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'",
]));
// Remove PHP fingerprint
header_remove("X-Powered-By");
}
// ── Input Hardening patterns ────────────────────────────────────
// 1. Integer IDs - cast immediately
function getIdFromRequest(string $key): int {
$id = filter_input(INPUT_GET, $key, FILTER_VALIDATE_INT, [
"options" => ["min_range" => 1]
]);
if ($id === false || $id === null) {
http_response_code(400);
die("Invalid ID.");
}
return $id;
}
$postId = getIdFromRequest("id"); // guaranteed positive int
// 2. Slug validation - only a-z, 0-9, hyphen
function getSlugFromRequest(): string {
$slug = trim($_GET["slug"] ?? "");
if (!preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug)) {
http_response_code(400);
die("Invalid slug.");
}
return $slug;
}
// 3. File path - never use user input in file paths!
// ❌ Path traversal vulnerability:
$file = __DIR__ . "/" . $_GET["file"]; // ?file=../../etc/passwd
// ✅ Allowlist or basename:
$allowedFiles = ["privacy.txt", "terms.txt", "license.txt"];
$filename = basename($_GET["file"] ?? "");
if (!in_array($filename, $allowedFiles, true)) {
http_response_code(404); die();
}
$content = file_get_contents(__DIR__ . "/legal/" . $filename);
// 4. Redirect - open redirect prevention
function safeRedirect(string $url): void {
// Only allow relative paths - not external URLs
if (str_starts_with($url, "http") || str_starts_with($url, "//")) {
$url = "/"; // block open redirect
}
header("Location: " . $url, replace: true, response_code: 302);
exit;
}Quick Quiz
Tip
Tip
Practice Secure Headers Input Hardening in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Secure Headers & Input Hardening
Practice Task
Note
Practice Task - (1) Write a working example of Secure Headers Input Hardening from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Secure Headers Input Hardening is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?