PHP

Enhance Security with HTTP Headers

Boost your web application's security posture by setting essential HTTP security headers like HSTS, CSP, and X-Frame-Options to mitigate common web vulnerabilities.

<?php
// Prevent page from being loaded in an iframe to avoid clickjacking
header('X-Frame-Options: DENY');

// Prevent browsers from MIME-sniffing a response away from the declared content-type
header('X-Content-Type-Options: nosniff');

// Enable XSS protection for older browsers (modern browsers have built-in XSS auditors)
header('X-XSS-Protection: 1; mode=block');

// Force HTTPS for a specified duration, preventing MITM downgrade attacks
// The 'max-age' is in seconds (e.g., 1 year = 31536000)
// 'includeSubDomains' is optional but recommended
// header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');

// Content Security Policy (CSP) to mitigate XSS and data injection attacks
// This is a minimal example, CSP can be very complex.
// header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; object-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;");

// Example content
echo "<h1>Secure Page Content</h1>";
echo "<p>These headers help protect against common web vulnerabilities.</p>";
?>
How it works: This code demonstrates how to set crucial HTTP security headers using PHP. `X-Frame-Options` prevents clickjacking, `X-Content-Type-Options` stops MIME sniffing, and `X-XSS-Protection` offers an extra layer of defense against XSS in older browsers. Although commented out, `Strict-Transport-Security` (HSTS) enforces HTTPS, and `Content-Security-Policy` (CSP) is vital for defining trusted sources of content, significantly reducing XSS and data injection risks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs