PHP
Essential HTTP Security Headers in PHP
Enhance your PHP application's security by adding critical HTTP response headers like Content-Security-Policy, X-Frame-Options, HSTS, and X-Content-Type-Options to mitigate common web vulnerabilities.
<?php
// Strict-Transport-Security (HSTS): Enforce HTTPS
// Max-age: 1 year (31536000 seconds), includeSubDomains: Apply to subdomains too
header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');
// X-Frame-Options: Prevent clickjacking
// DENY: Most restrictive, no framing allowed
// SAMEORIGIN: Only frame if the embedding page is from the same origin
header('X-Frame-Options: DENY');
// X-Content-Type-Options: Prevent MIME sniffing attacks
// nosniff: Forces the browser to use the Content-Type header value
header('X-Content-Type-Options: nosniff');
// Content-Security-Policy (CSP): Mitigate XSS and data injection attacks
// Default-src: What sources are allowed for all content types
// script-src: Allowed sources for JavaScript
// object-src: Allowed sources for <object>, <embed>, <applet>
// base-uri: Allowed <base> element URLs
// form-action: Allowed targets for form submissions
// For a real app, tailor this meticulously. Example is highly restrictive.
header("Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'");
// Referrer-Policy: Control how much referrer information is sent
// no-referrer-when-downgrade: Send full URL for same-origin requests, but not for HTTP->HTTPS
header('Referrer-Policy: no-referrer-when-downgrade');
// X-XSS-Protection: (Mostly deprecated by CSP, but good as a fallback)
// Deprecated for modern browsers, rely on CSP. '0' disables it.
header('X-XSS-Protection: 0');
// Example content
echo "<h1>Welcome to our secure page!</h1>";
echo "<p>These headers help protect your users.</p>";
?>
How it works: HTTP Security Headers are crucial for protecting web applications against various common attacks. This PHP snippet demonstrates how to set several key headers using the `header()` function. `Strict-Transport-Security` enforces HTTPS, `X-Frame-Options` prevents clickjacking, `X-Content-Type-Options` stops MIME sniffing, and `Content-Security-Policy` (CSP) is a powerful tool against Cross-Site Scripting (XSS) by defining allowed content sources. Proper implementation of these headers significantly hardens your application's front-end security posture.