PHP
Preventing Clickjacking Attacks with X-Frame-Options
Protect your website from malicious clickjacking attacks by setting the `X-Frame-Options` HTTP header, controlling if your page can be embedded in an iframe.
<?php
// Option 1: Deny any framing of the page
// header('X-Frame-Options: DENY');
// Option 2: Allow framing only by pages from the same origin
header('X-Frame-Options: SAMEORIGIN');
// Option 3: (Less secure, deprecated for modern browsers) Allow framing by a specific URI
// header('X-Frame-Options: ALLOW-FROM https://trusted.example.com');
// Note: ALLOW-FROM is not supported by all modern browsers.
// For broader support, consider using Content Security Policy's frame-ancestors directive.
echo "<!DOCTYPE html>";
echo "<html lang='en'>";
echo "<head>";
echo " <meta charset='UTF-8'>";
echo " <title>Secure Page</title>";
echo "</head>";
echo "<body>";
echo " <h1>This is a secure page protected from Clickjacking.</h1>";
echo " <p>This page should not be embeddable in an iframe from another domain.</p>";
echo " <button onclick='alert(\"Button clicked!\")'>Click Me</button>";
echo "</body>";
echo "</html>";
?>
How it works: Clickjacking is an attack where a malicious website overlays a transparent iframe containing a target website over its own content, tricking a user into clicking on elements of the target site. The `X-Frame-Options` HTTP response header is a crucial defense. This PHP snippet demonstrates how to set this header to `SAMEORIGIN`, which instructs the browser to only allow the page to be framed by other pages originating from the same domain. Setting it to `DENY` would completely prevent any framing. This prevents attackers from embedding your content within their sites to hijack user interactions.