I am trying to add a token to my forms in order to prevent CSRF attacks
But the token validation isn't working
Here is the input field which holds the token
<input type="hidden" name="auth_token" value="<?php echo $_SESSION['auth_token']; ?>">
And here is the token validation code
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate token to avoid CSRF
$auth_token = $_POST["auth_token"];
if (!$auth_token || $auth_token != $_SESSION['auth_token']) {
// show an error message
echo '<h1 class="error">Error: invalid form submission</h1><p>Your request was denied as this request could not be verified.</p>';
// return 405 http status code
header($_SERVER['SERVER_PROTOCOL'] . ' 405 Method Not Allowed');
exit();
}
// process form here
}
It doesn't work and it returns the error message in the if
block