I want to correctly implement a CSRF token with validation into the forms of my website.
Here is how the token is generated:
$_SESSION["token"] = bin2hex(random_bytes(32));
Here is the hidden field inside of my form that changes every time the form is submitted or every time the page is refreshed:
<input type="hidden" name="token" value="<?=$_SESSION["token"]?>">
Here is an example of what is seen when the form in inspected:
<input type="hidden" name="token" value="3c33c5dc178293f9bcaff264b90836780887efe16c339d01c1cbe34bf9ecbddd">
Now when the form is submitted this is the validation I put in place for the token:
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//CSRF TOKEN + VALIDATION
if (!isset($_POST['token']) || ($_POST['token'] !== $_SESSION['token'])) {
exit;
}
I want to know if this validating that the ($_POST['token'] !== $_SESSION['token'])
?
Because when I change my script to this:
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//CSRF TOKEN + VALIDATION
if (!isset($_POST['token'])) {
exit;
}
Nothing changes and the form is submitted exactly like before.
Is my original IF statement only checking if a $_POST
isset?
If so, is this still a secure way to protect against CSRF attacks?