PHP

Enhance Security with Critical HTTP Response Headers

Configure essential HTTP security headers like X-Frame-Options, X-Content-Type-Options, and Content-Security-Policy to mitigate common web vulnerabilities.

<?php
// Prevent clickjacking by disallowing framing
header('X-Frame-Options: DENY');

// Prevent MIME-type sniffing, forcing the browser to respect Content-Type header
header('X-Content-Type-Options: nosniff');

// Prevent XSS attacks via reflected XSS, by telling browser to activate its XSS filter
// Note: X-XSS-Protection is largely deprecated in favor of CSP, but still has some fallback use.
// It's recommended to primarily rely on CSP.
// header('X-XSS-Protection: 1; mode=block');

// Control when and how much referrer information is sent with requests
header('Referrer-Policy: no-referrer-when-downgrade');

// Set a basic Content Security Policy (CSP) header
// This is a powerful header that prevents XSS and other injection attacks.
// It can be very complex; this is a simple example.
// 'default-src' specifies default sources for all content types.
// 'self' means only resources from the same origin are allowed.
// 'unsafe-inline' and 'unsafe-eval' are often needed for older apps or specific libraries,
// but should be avoided if possible, or limited (e.g., by using nonces or hashes).
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'");

// If using HSTS (HTTP Strict Transport Security), only apply after ensuring site is fully HTTPS.
// This header tells browsers to always use HTTPS for your domain for a specified duration.
// header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');


// Example content
echo "<h1>Secure Page Content</h1>";
echo "<p>This page is served with enhanced security headers.</p>";
?>
How it works: This snippet demonstrates how to set crucial HTTP security headers in PHP to bolster web application defense. `X-Frame-Options` prevents clickjacking, `X-Content-Type-Options` thwarts MIME-sniffing attacks, and `Referrer-Policy` manages referrer information leakage. The `Content-Security-Policy` (CSP) header is particularly powerful, allowing you to define trusted sources for various content types (scripts, styles, images), significantly reducing the risk of XSS and data injection attacks by blocking unauthorized resources. The `Strict-Transport-Security` (HSTS) header (commented out) ensures that browsers always connect via HTTPS.

Need help integrating this into your project?

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

Hire DigitalCodeLabs