Content Security Policy (CSP) Directive Regex for PHP
/^(default-src|script-src|style-src|img-src|connect-src|font-src|object-src|media-src|frame-src|child-src|form-action|frame-ancestors|base-uri|report-uri|report-to|upgrade-insecure-requests|block-all-mixed-content|sandbox|worker-src|manifest-src|prefetch-src)(?:\s+(.+))?$/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching content security policy (csp) directive, ported and verified for PHP. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your PHP project — whether you're validating in a Laravel validator, a WordPress plugin, or a standalone PHP script.
Php Implementation
<?php
// Content Security Policy (CSP) Directive
// ReDoS-safe | RegexVault — Security > Security Headers
define('CONTENT_SECURITY_POLICY_CSP_DIRECTIVE_PATTERN', '/^(default-src|script-src|style-src|img-src|connect-src|font-src|object-src|media-src|frame-src|child-src|form-action|frame-ancestors|base-uri|report-uri|report-to|upgrade-insecure-requests|block-all-mixed-content|sandbox|worker-src|manifest-src|prefetch-src)(?:\s+(.+))?$/');
function validate_content_security_policy_csp_directive(string $input): bool {
return (bool) preg_match(CONTENT_SECURITY_POLICY_CSP_DIRECTIVE_PATTERN, $input);
}
// Example
var_dump(validate_content_security_policy_csp_directive("default-src 'self'")); // bool(true)Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
default-src 'self' | evil-src 'self' |
script-src 'self' https://cdn.example.com 'nonce-abc123' | src 'self' |
object-src 'none' | — |
upgrade-insecure-requests | — |
When to use this pattern
This pattern is drawn from the Security > Security Headers category and carries a ReDoS-safe certification. That matters for PHP developers because especially relevant in PHP where PCRE backtracking limits can trigger silent failures on malicious input. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
'unsafe-inline' and 'unsafe-eval' negate much of CSP's protection. Prefer nonce-based CSP where a random nonce is generated per request. The CSP Evaluator tool (from Google) checks CSP policies for weaknesses.
Technical Notes
CSP source keywords: 'self' (same origin), 'none' (block all), 'unsafe-inline' (dangerous), 'unsafe-eval' (dangerous), 'nonce-{base64}' (nonce), 'sha256-{hash}' (hash). A strong CSP eliminates most XSS attack surfaces. object-src 'none' and base-uri 'self' are critical.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern