<!doctype html>
<meta charset="utf-8">
<title> T CSRF_TEST.php </title>
<style> html * { font-size:1.75rem; font-family:monospace; } </style>
<?php
// Generate a CSRF token and store it in a cookie
$csrfToken = bin2hex(random_bytes(32));
setcookie("csrfToken", $csrfToken, time() + 3600);
?>
<form action="CSRF_TEST.php" method="POST">
<input type="hidden" name="csrfToken" value="<?php echo $_COOKIE['csrfToken']; ?>">
<input type="submit" value="Submit" onclick="refreshPage()">
</form>
<?php
echo "<br>";
$TOKEN = $_POST["csrfToken"];
echo "<br>TOKEN= " . $TOKEN;
$TOKEN2 = $_COOKIE['csrfToken'];
echo "<br>TOKEN2= " . $TOKEN2;
// On the server side, verify the CSRF token
if ($_POST['csrfToken'] !== $_COOKIE['csrfToken']) {
// CSRF token mismatch
// Reject the request
echo "<br>";
echo "Reject the request";
}
else
{
echo "APPROVED REQUEST";
}
?>
<script>
function refreshPage() {
window.location.replace("CSRF_TEST.php");
}
</script>
I am running this program and obtain two different value in the conditional ($_POST[‘csrfToken’] !== $_COOKIE[‘csrfToken’]) test . As I know the generative CSRF token is stored in cookie then the same is POST to php and i cannot realize why the values are different.