I am writing app in PHP 7.3 where users forms to submit data using forms. These forms have to be protected using CSRF.
When a request is made, I want first to try to validate the CSRF token ($_SESSION against $_POST or $_GET) and store the result in a variable. Then I want to generate a new token and store it in the $_SESSION.
The logic of the app is to validate CSRF, generate new CSRF, check if POST is made and the validation were sucessful, echo multiple forms to output.
I tried to simplify the code, but I have access to only one server, so I am unable to test, whether this is a coding or server error.
<?php
session_start();
echo $_SESSION["a"];
$validateCsrf = false;
if (!empty($_POST["a"]) && $_SESSION["a"] === $_POST["a"]) {
$validateCsrf = true;
}
$_SESSION["a"] = random_int(100000000,999999999);
echo $_SESSION["a"];
?>
I expect output of this to first show the old CSRF token and then the new CSRF token. If you reload the page, the second token should "move" to the first place as it becomes the old one that is getting validated, however this does not happen there is some other output.
Example output:
209959590 576642097
534067777 374285992
Expected output:
209959590 576642097
576642097 374285992
What am I doing wrong?