CSP Builder — PHP source
Build a Content-Security-Policy header interactively. Toggle directives, add sources, see the assembled header in real time — with a security score that flags unsafe sources.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* csp-builder — Content-Security-Policy assembly, parsing, linting and scoring.
*
* Language: PHP 7.4+ (standard library only).
* CosmoDev polyglot showcase port of the `csp-builder` tool, ported from
* src/lib/csp-builder.ts (the canonical TypeScript implementation).
*
* A CSP is an associative array of directive name -> source list; PHP arrays
* preserve insertion order, which is exactly what the TS Record relies on for
* unknown-directive ordering in csp_build(). csp_parse() is lenient by design
* so a pasted real-world header always yields something editable. Functions
* carry the csp_ prefix (like the C port) so many tool pages can coexist.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
declare(strict_types=1);
/**
* The directive catalog, in canonical build/display order: name => kind.
* kind is 'sources', 'url' or 'flag'; flags emit as a bare name.
* Descriptions, risk labels and default sources are UI metadata, omitted.
*/
const CSP_CATALOG = [
'default-src' => 'sources', 'script-src' => 'sources', 'style-src' => 'sources',
'img-src' => 'sources', 'connect-src' => 'sources', 'font-src' => 'sources',
'frame-src' => 'sources', 'media-src' => 'sources', 'object-src' => 'sources',
'base-uri' => 'sources', 'form-action' => 'sources', 'frame-ancestors' => 'sources',
'report-uri' => 'url', 'upgrade-insecure-requests' => 'flag',
'block-all-mixed-content' => 'flag',
];
/**
* Assemble a policy map into the `Content-Security-Policy` header value.
* Known directives emit in catalog order, unknown ones after them in
* insertion order. Flag directives emit as a bare name; source/url directives
* with an empty list are omitted (a valueless directive is invalid CSP).
* An empty map yields an empty string.
*/
function csp_build(array $directives): string
{
$parts = [];
$emit = function (string $name) use ($directives, &$parts): void {
$sources = $directives[$name] ?? null;
if ($sources === null) {
return;
}
if ((CSP_CATALOG[$name] ?? null) === 'flag') {
$parts[] = $name;
} elseif ($sources !== []) {
$parts[] = $name . ' ' . implode(' ', $sources);
}
};
foreach (array_keys(CSP_CATALOG) as $name) {
$emit($name);
}
foreach (array_keys($directives) as $name) {
if (!array_key_exists($name, CSP_CATALOG)) {
$emit($name);
}
}
return implode('; ', $parts);
}
/**
* Parse a CSP header value back into a policy map. Lenient: splits on
* semicolons and whitespace, lowercases directive names, ignores empty
* tokens, and strips an optional leading `Content-Security-Policy:` label so
* a pasted full header line works. Duplicate directives keep only the first
* occurrence (matching how browsers honor them). Never throws; garbage in, [] out.
*/
function csp_parse(string $header): array
{
$text = trim($header);
if (preg_match('/^content-security-policy\s*:/i', $text)) {
$text = substr($text, strpos($text, ':') + 1);
}
$out = [];
foreach (explode(';', $text) as $token) {
$words = preg_split('/\s+/', trim($token), -1, PREG_SPLIT_NO_EMPTY);
if ($words === false || $words === []) {
continue;
}
$name = strtolower($words[0]);
if (!array_key_exists($name, $out)) {
$out[$name] = array_slice($words, 1);
}
}
return $out;
}
/** Sources treated as security-weakening, compared case-insensitively. */
const CSP_RISKY_SOURCES = ["'unsafe-inline'", "'unsafe-eval'", 'data:', 'http:', '*'];
/**
* True when a source weakens the policy: 'unsafe-inline', 'unsafe-eval',
* 'data:', 'http:', the bare wildcard '*', or any insecure http:// URL.
*/
function csp_is_risky_source(string $source): bool
{
$s = strtolower(trim($source));
return in_array($s, CSP_RISKY_SOURCES, true) || strpos($s, 'http://') === 0;
}
/** Short human explanation for each risky source (tooltip text in the UI). */
const CSP_RISK_EXPLANATIONS = [
"'unsafe-inline'" => "Allows inline <script>/<style> and event handlers - defeats most of CSP's XSS protection.",
"'unsafe-eval'" => 'Allows eval() and similar code execution - weakens XSS protection.',
'*' => 'Allows every origin - effectively no restriction for this directive.',
'data:' => 'data: URIs can carry arbitrary payloads and are same-origin - attackers can smuggle content through them.',
'http:' => 'Allows insecure origins - a network attacker can inject or tamper with subresources.',
];
/** Explanation for any risky source; falls back to the generic insecure-origin text. */
function csp_risk_explanation(string $source): string
{
return CSP_RISK_EXPLANATIONS[strtolower(trim($source))]
?? 'Insecure http:// URL - traffic can be tampered with in transit.';
}
/**
* Lint a policy: warns when default-src is missing (unset directives fall
* back to the browser's allow-everything default) and flags every risky
* source. Each issue is a map with directive ('' = policy-wide), source
* (null = policy-wide) and message.
*/
function csp_validate(array $directives): array
{
$issues = [];
if (!array_key_exists('default-src', $directives)) {
$issues[] = [
'directive' => '',
'source' => null,
'message' => "No default-src - every directive you don't set explicitly falls back to the browser's permissive default.",
];
}
foreach ($directives as $name => $sources) {
foreach ($sources as $src) {
if (csp_is_risky_source($src)) {
$issues[] = [
'directive' => $name,
'source' => $src,
'message' => $name . ': ' . $src . ' weakens this policy - ' . csp_risk_explanation($src),
];
}
}
}
return $issues;
}
/**
* Security score, 0-100. Starts at 100; each risky source subtracts its
* penalty (insecure http:// URLs subtract 10), and a missing default-src
* subtracts 10. Clamped to 0-100. Deterministic.
*/
function csp_security_score(array $directives): int
{
$penalties = ["'unsafe-inline'" => 20, "'unsafe-eval'" => 15, '*' => 20, 'data:' => 10, 'http:' => 10];
$score = 100;
if (!array_key_exists('default-src', $directives)) {
$score -= 10;
}
foreach ($directives as $sources) {
foreach ($sources as $src) {
$s = strtolower(trim($src));
$score -= $penalties[$s] ?? (strpos($s, 'http://') === 0 ? 10 : 0);
}
}
return max(0, min(100, $score));
}
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 →