Skip to content

Security Headers Analyzer — PHP source

Paste HTTP response headers to analyze security posture. Checks CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Permissions-Policy.

This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.

<?php
/**
 * security-headers — HTTP response-header analysis and grading.
 * Language: PHP 7.4+ (standard library only). CosmoDev polyglot showcase port
 * of the `security-headers` tool, ported from src/lib/security-headers.ts: the
 * exact A/B/C/F verdicts, weighted score, and fix list match the lib byte for
 * byte; catalog blurbs are omitted for brevity.
 * display source — part of CosmoDev's polyglot tool pages.
 */
declare(strict_types=1);
// Grade points for the weighted overall score; ONE_YEAR is the strong HSTS
// max-age floor. SECURITY_HEADERS carries [grader, weight] in display order;
// the "why it matters" blurbs live in src/lib/security-headers.ts.
const GRADE_POINTS = ['A' => 100, 'B' => 70, 'C' => 40, 'F' => 0];
const ONE_YEAR = 31536000;
const BEST = 'Best practice met - nothing to change.';
const REFERRER_STRICT = ['no-referrer', 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin'];
const REFERRER_WEAK = ['origin', 'origin-when-cross-origin', 'no-referrer-when-downgrade'];
const SECURITY_HEADERS = [
    'Strict-Transport-Security' => ['gradeHsts', 1.5], 'Content-Security-Policy' => ['gradeCsp', 2],
    'X-Frame-Options' => ['gradeFrameOptions', 1], 'X-Content-Type-Options' => ['gradeContentTypeOptions', 1],
    'Referrer-Policy' => ['gradeReferrerPolicy', 1], 'Permissions-Policy' => ['gradePermissionsPolicy', 1],
    'X-XSS-Protection' => ['gradeXssProtection', 0.5], 'Cross-Origin-Opener-Policy' => ['gradeCoop', 1],
];

/** Parse a raw header block into a lowercased-name map: the `HTTP/1.1 200 OK`
 * status line and colon-less lines are ignored, an indented line continues the
 * previous header (RFC 7230 obs-fold), and a repeated name joins ", ". */
function parseHeaders(?string $raw): array
{
    $headers = []; $lastName = null;
    foreach (preg_split('/\r?\n/', $raw ?? '') as $line) {
        if (preg_match('/^\s/', $line) === 1) { // folded continuation line (obs-fold)
            if ($lastName !== null) $headers[$lastName] = trim(($headers[$lastName] ?? '') . ' ' . trim($line));
        } elseif (($colon = strpos($line, ':')) !== false && ($name = strtolower(trim(substr($line, 0, $colon)))) !== '') {
            $value = trim(substr($line, $colon + 1));
            $headers[$name] = isset($headers[$name]) ? "{$headers[$name]}, {$value}" : $value;
            $lastName = $name;
        }
    }
    return $headers;
}
function gradeHsts(?string $v): array
{
    if ($v === null) return ['C', 'Missing - the browser accepts plain HTTP, so the first visit (and SSL-strip attacks) can downgrade the connection.', 'Add: strict-transport-security: max-age=31536000; includeSubDomains; preload'];
    if (!preg_match('/max-age\s*=\s*(\d+)/i', $v, $m)) return ['B', "Present but malformed - no readable max-age directive ({$v}).", 'Use: strict-transport-security: max-age=31536000; includeSubDomains'];
    if (($maxAge = (int) $m[1]) === 0) return ['F', 'max-age=0 actively deletes the HSTS policy - the site opts out of HTTPS-only enforcement.', 'Raise max-age to at least 31536000 (one year).'];
    $subs = (bool) preg_match('/;\s*includesubdomains/i', $v); if ($maxAge < ONE_YEAR) return ['B', 'Present with max-age=' . $maxAge . 's (< 1 year)' . ($subs ? ' and includeSubDomains' : '') . ' - a shorter window weakens the guarantee.', 'Raise max-age to 31536000 (one year) or more.'];
    if (!$subs) return ['B', 'Strong max-age (>= 1 year), but includeSubDomains is missing - subdomains stay downgradable.', 'Append ; includeSubDomains once every subdomain serves HTTPS.'];
    return ['A', 'Strong: max-age >= 1 year + includeSubDomains' . (preg_match('/;\s*preload/i', $v) ? ' + preload - eligible for the browser preload list.' : '. Add preload to join the browser preload list.'), BEST];
}
function gradeCsp(?string $v): array
{
    if ($v === null) return ['C', 'Missing - no restriction on where scripts and resources load from, so injected markup runs at full power.', "Add a policy, e.g.: content-security-policy: default-src 'none'; script-src 'self'; ..."];
    $inline = (bool) preg_match("/'unsafe-inline'/i", $v); $evals = (bool) preg_match("/'unsafe-eval'/i", $v);
    if ($inline && $evals) return ['F', "Actively harmful - 'unsafe-inline' + 'unsafe-eval' together re-allow inline injection and string evaluation, gutting the policy while it still looks present.", "Remove 'unsafe-inline' and 'unsafe-eval'; use nonces or hashes for inline scripts."];
    if ($inline || $evals) { $c = $inline ? "'unsafe-inline'" : "'unsafe-eval'";
        return ['B', "Present but weak - {$c} punches a hole through the anti-XSS guarantee.", "Remove {$c}; use nonces or hashes for legitimate inline code."]; }
    if (!preg_match('/(^|\s)default-src\s/i', $v)) return ['B', 'Present with no default-src - resource types not listed explicitly fall back to the browser permissive default.', "Start the policy with default-src 'none' or 'self', then allow what you need."];
    return ['A', 'Strong - a default-src fallback with no unsafe-inline / unsafe-eval escape hatches.', BEST];
}
function gradeFrameOptions(?string $v): array
{
    if ($v === null) return ['C', 'Missing - any site can embed this page in an iframe and overlay it (clickjacking).', 'Add: x-frame-options: DENY (or SAMEORIGIN if you embed yourself)'];
    if (($u = strtoupper(trim($v))) === 'DENY' || $u === 'SAMEORIGIN') return ['A', "Strong - {$u} blocks framing by other origins.", BEST];
    if (strpos($u, 'ALLOW-FROM') === 0) return ['B', 'ALLOW-FROM is deprecated and modern browsers ignore it - the page is effectively frameable.', 'Replace with a CSP frame-ancestors directive (x-frame-options: DENY as fallback).'];
    return ['B', "Unrecognized value ({$v}) - browsers ignore it, leaving the page frameable.", 'Use DENY or SAMEORIGIN.'];
}
function gradeContentTypeOptions(?string $v): array
{
    if ($v === null) return ['C', 'Missing - browsers may sniff uploaded content into executable types.', 'Add: x-content-type-options: nosniff'];
    if (strtolower(trim($v)) === 'nosniff') return ['A', 'Strong - MIME sniffing is off; the declared Content-Type is final.', BEST];
    return ['B', "Present but the value ({$v}) is not nosniff, so browsers ignore the header.", 'Send exactly: x-content-type-options: nosniff'];
}
function gradeReferrerPolicy(?string $v): array
{
    if ($v === null) return ['C', 'Missing - older browsers default to leaking the full URL to whatever site the user navigates to.', 'Add: referrer-policy: strict-origin-when-cross-origin (or no-referrer)'];
    if (($p = strtolower(trim($v))) === 'unsafe-url') return ['F', 'Actively harmful - unsafe-url sends the full URL (including IDs and tokens in query strings) to every destination, even on plain HTTP.', 'Use strict-origin-when-cross-origin or no-referrer instead.'];
    if (in_array($p, REFERRER_STRICT, true)) return ['A', "Strong - {$p} leaks at most the origin cross-origin.", BEST];
    if (in_array($p, REFERRER_WEAK, true)) return ['B', "Present but leaky - {$p} still shares the full URL in some same- or cross-origin cases.", 'Tighten to strict-origin-when-cross-origin, strict-origin, same-origin, or no-referrer.'];
    return ['B', "Unrecognized value ({$v}) - browsers fall back to their default policy.", 'Use one of the standard directives, e.g. strict-origin-when-cross-origin.'];
}
function gradePermissionsPolicy(?string $v): array
{
    if ($v === null) return ['C', 'Missing - powerful features (camera, geolocation, payment...) default to the browser policy, not yours.', 'Add: permissions-policy: camera=(), microphone=(), geolocation=()'];
    if (($p = strtolower((string) preg_replace('/\s+/', '', $v))) === '') return ['B', 'Present but empty - no feature is restricted, so it declares nothing.', 'List the features to switch off, e.g. camera=(), microphone=().'];
    if ($p === '*' || strpos($p, '=*') !== false) return ['B', 'Present but permissive - a =* wildcard re-allows the listed feature(s) everywhere.', 'Use an empty allowlist () or a specific origin instead of *.'];
    return ['A', 'Strong - the policy restricts at least one powerful feature.', BEST];
}
function gradeXssProtection(?string $v): array
{
    if ($v === null) return ['A', 'Correctly omitted - the header is deprecated; modern browsers removed the XSS Auditor it drove.', 'Nothing to change - rely on Content-Security-Policy instead.'];
    if (($t = trim($v)) === '0' || substr($t, 0, 2) === '0;') return ['A', "Explicitly disabled ('0') - the right call for a deprecated header old browsers still honor.", 'Nothing to change - or remove the header entirely.'];
    if ($t !== '' && $t[0] === '1') return ['B', "Deprecated - '1; mode=block' is ignored by modern browsers and the old Auditor had cross-site leaks of its own.", "Send '0' or drop the header; use Content-Security-Policy for XSS defense."];
    return ['B', "Present with an unrecognized value ({$v}) - remove the deprecated header.", "Send '0' or drop the header entirely."];
}
function gradeCoop(?string $v): array
{
    if ($v === null) return ['C', 'Missing - pages that open or are opened by other origins share a browsing context with them.', 'Add: cross-origin-opener-policy: same-origin'];
    if (($p = strtolower(trim($v))) === 'same-origin') return ['A', 'Strong - the window handle is isolated from cross-origin openers.', BEST];
    if ($p === 'same-origin-allow-popups') return ['B', 'Partially isolated - popups you open keep a reference to this window.', 'Use same-origin unless you genuinely need cross-origin popup handles.'];
    if ($p === 'unsafe-none') return ['B', 'Explicit opt-out - unsafe-none restores the shared browsing context COOP exists to cut.', 'Use same-origin unless a documented integration requires shared handles.'];
    return ['B', "Unrecognized value ({$v}) - browsers treat it as no COOP.", 'Use same-origin.'];
}
/** Analyze a raw HTTP response-header block: one {name, value, grade,
 * explanation, recommendation} row per catalog header, a weighted-average
 * 0-100 score, and one fix recommendation per header below grade A. */
function analyzeHeaders(?string $raw): array
{
    $parsed = parseHeaders($raw); $headers = []; $weighted = 0.0;
    foreach (SECURITY_HEADERS as $name => [$grader, $weight]) {
        [$grade, $explanation, $recommendation] = $grader($value = $parsed[strtolower($name)] ?? null);
        $weighted += GRADE_POINTS[$grade] * $weight;
        $headers[] = ['name' => $name, 'value' => $value, 'grade' => $grade, 'explanation' => $explanation, 'recommendation' => $recommendation];
    }
    // PHP round() is half-away-from-zero: identical to JS Math.round for x >= 0.
    $score = (int) round($weighted / array_sum(array_column(SECURITY_HEADERS, 1)));
    $recs = array_map(fn (array $h) => $h['recommendation'], array_values(array_filter($headers, fn (array $h) => $h['grade'] !== 'A')));
    return ['headers' => $headers, 'grade' => $score >= 90 ? 'A' : ($score >= 70 ? 'B' : ($score >= 45 ? 'C' : 'F')), 'score' => $score, 'recommendations' => $recs];
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →