PHP
Configure Essential Security HTTP Headers
Enhance the overall security posture of your web application by explicitly setting crucial HTTP response headers like X-Frame-Options, X-Content-Type-Options, and HSTS.
<?php
// --- 1. X-Frame-Options: Prevent Clickjacking ---
// Deny framing of the page
header('X-Frame-Options: DENY');
// Or allow framing only from the same origin: header('X-Frame-Options: SAMEORIGIN');
// --- 2. X-Content-Type-Options: Prevent MIME-sniffing attacks ---
// Forces the browser to strictly follow the Content-Type header
header('X-Content-Type-Options: nosniff');
// --- 3. Strict-Transport-Security (HSTS): Enforce HTTPS ---
// This tells browsers to only connect via HTTPS for a given duration.
// max-age is in seconds (e.g., 1 year = 31536000).
// includeSubDomains is optional, preload is for HSTS Preload List submission.
header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');
// --- 4. Referrer-Policy: Control referrer information leakage ---
// 'no-referrer-when-downgrade' is a good balance
header('Referrer-Policy: no-referrer-when-downgrade');
// --- 5. Permissions-Policy (formerly Feature-Policy): Control browser features ---
// Example: disable camera, microphone, geolocation for all origins
// Consider carefully which features to allow/deny.
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
// --- 6. Content-Security-Policy (CSP): (As detailed in a separate snippet) ---
// header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline';");
// Your application logic here
echo "<h1>Secure Page Content</h1>";
echo "<p>These headers are set to enhance security against common web vulnerabilities.</p>";
?>
How it works: HTTP security headers provide an additional layer of defense by instructing browsers on how to behave when interacting with your site. `X-Frame-Options` prevents clickjacking by controlling whether your site can be embedded in an iframe. `X-Content-Type-Options: nosniff` stops browsers from trying to "guess" the MIME type, which can prevent XSS attacks. `Strict-Transport-Security` (HSTS) mandates the use of HTTPS for a specified duration, protecting against downgrade attacks. `Referrer-Policy` manages the information sent in the Referer header, and `Permissions-Policy` allows you to control browser features accessible to the page.