PHP
Implement Content Security Policy (CSP) in PHP
Enhance web application security by implementing Content Security Policy (CSP) headers in PHP, mitigating XSS and data injection attacks by controlling allowed content sources.
<?php
// --- Option 1: Basic CSP for common scenarios ---
// header("Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self' https://fonts.gstatic.com;");
// --- Option 2: More robust CSP with nonce for inline scripts/styles (recommended) ---
// Generate a unique nonce for each request
// Nonce should be sufficiently random and cryptographically secure.
$nonce = base64_encode(random_bytes(16));
// Define CSP directives
$cspDirectives = [
"default-src 'self'", // Allow content only from the same origin
"script-src 'self' 'nonce-{$nonce}' https://trusted-cdn.com", // Allow scripts from self and trusted CDN, plus inline scripts with matching nonce
"style-src 'self' 'nonce-{$nonce}' https://fonts.googleapis.com", // Allow styles from self, trusted CDN, plus inline styles with matching nonce
"img-src 'self' data: https://cdn.example.com", // Allow images from self, data URIs, and a specific CDN
"font-src 'self' https://fonts.gstatic.com", // Allow fonts from self and Google Fonts
"connect-src 'self' api.example.com", // Allow AJAX/WebSocket connections to self and specific API
"frame-src 'self' youtube.com", // Allow iframes from self and YouTube
"object-src 'none'", // Block all plugin content
"base-uri 'self'", // Restrict URLs that can be used in <base> element
"form-action 'self'", // Restrict URLs that can be used as the target of form submissions
"frame-ancestors 'self'", // Prevent clickjacking by disallowing embedding in iframes from other origins
// "report-uri /csp-report-endpoint", // Optional: Report violations to a specific URL
// "block-all-mixed-content", // Optional: Block HTTP assets on HTTPS pages
];
// Combine directives into a single header value
$cspHeader = "Content-Security-Policy: " . implode('; ', $cspDirectives);
// Set the CSP header
header($cspHeader);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSP Example</title>
<style nonce="<?php echo $nonce; ?>">
body { font-family: sans-serif; }
.content { padding: 20px; border: 1px solid #ccc; }
</style>
</head>
<body>
<div class="content">
<h1>Content Security Policy Demo</h1>
<p>This page uses CSP to prevent unauthorized content.</p>
<script nonce="<?php echo $nonce; ?>">
// This inline script is allowed because of the matching nonce.
// document.addEventListener('DOMContentLoaded', function() {
// console.log('DOM fully loaded and parsed. CSP is active.');
// });
</script>
<!-- <script>alert('This inline script would be blocked if nonce does not match!');</script> -->
</div>
</body>
</html>
How it works: This PHP snippet demonstrates implementing Content Security Policy (CSP) via HTTP headers. CSP is a powerful security layer that helps mitigate XSS and data injection attacks by specifying which content sources (scripts, styles, images, etc.) the browser is allowed to load. The example uses a nonce-based approach, generating a unique, cryptographically random value for each request. This nonce must be included in the CSP header and as an attribute on inline `<script>` and `<style>` tags, allowing them to execute while blocking any unauthorized or injected inline code, significantly enhancing web application security.