PHP

Configuring Content Security Policy (CSP)

Boost your web application's security against XSS and data injection by implementing a robust Content Security Policy (CSP) using HTTP headers.

<?php
// Define your CSP directives
// It's recommended to start with a strict policy and loosen it as needed.
// 'self' keyword restricts to the same origin.
$csp_directives = [
    "default-src 'self'", // Fallback for any resource types not explicitly defined
    "script-src 'self' https://trusted.cdn.com 'nonce-RANDOM_NONCE_VALUE'", // Allow scripts from self and a trusted CDN, with a nonce
    "style-src 'self' https://trusted.cdn.com 'unsafe-inline'", // Allow styles from self, trusted CDN, and inline styles (use 'nonce' if possible)
    "img-src 'self' data: https://cdn.example.com", // Allow images from self, data URIs, and a CDN
    "font-src 'self' https://fonts.gstatic.com", // Allow fonts from self and Google Fonts
    "connect-src 'self' https://api.example.com", // Allow AJAX/WebSockets to self and a trusted API
    "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
    "object-src 'none'", // Disallow <object>, <embed>, <applet>
    "base-uri 'self'", // Restrict the URLs that can be used in a document's <base> element
    "upgrade-insecure-requests" // Automatically upgrade insecure HTTP requests to HTTPS
];

// Join directives with a semicolon and space
$csp_header_value = implode('; ', $csp_directives);

// Send the Content-Security-Policy header
// For report-only mode (testing), use: header("Content-Security-Policy-Report-Only: " . $csp_header_value);
header("Content-Security-Policy: " . $csp_header_value);

// Important: Nonces should be generated per request and unique.
// Example for a nonce (replace with a secure, random generator for production):
// $nonce = base64_encode(random_bytes(16));
// In script-src, replace 'RANDOM_NONCE_VALUE' with actual $nonce
// And then include it in your script tags: <script nonce="<?= $nonce ?>">...</script>

// The rest of your PHP application logic and HTML goes here...
echo "<!DOCTYPE html>
";
echo "<html>
";
echo "<head><title>CSP Example</title></head>
";
echo "<body>
";
// ...
echo "</body>
";
echo "</html>
";
?>
How it works: This PHP snippet demonstrates how to configure a robust Content Security Policy (CSP) using the `Content-Security-Policy` HTTP header. It defines various directives like `default-src`, `script-src`, and `img-src` to control allowed resource origins, significantly mitigating XSS attacks. Using 'nonce' for scripts is highly recommended for stricter inline script security.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs