CSRF PROTECTED FORM
<?php
session_start();
// Set secure headers
header("X-Frame-Options: DENY"); // Prevent Clickjacking
header("X-XSS-Protection: 1; mode=block"); // Enable XSS protection
header("X-Content-Type-Options: nosniff"); // Prevent MIME-type sniffing
header("Referrer-Policy: no-referrer"); // Hide referrer info
header("Content-Security-Policy: default-src 'self'"); // Restrict resource loading
// Generate a CSRF token if not already set
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Check if the CSRF token is valid
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die("CSRF validation failed");
}
echo "Form submitted successfully!";
// Process the form securely here...
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSRF-Protected Form</title>
</head>
<body>
<h2>Secure Form with CSRF Protection</h2>
<form method="POST" action="">
<input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
Last updated