Strange thing with PHP token confirmation

  php, token, verification

Before submitting the form, I check if the token matches like this:

if (empty($_SESSION['token'])) {
    $_SESSION['token'] = bin2hex(random_bytes(32));
  };

if($request->token==$_SESSION['token']){
  
  ..some code..

}else{

echo "Token confirmation error!";

}

HTML:

<input class="mt-1 mb-1" type="hidden" name="token" value="<?php if($_SESSION['token']){echo $_SESSION['token'];}else{echo '';}; ?>">

And for some reason, else is always triggered, although in theory the check should occur when sending data. What could be the problem?

UPD.And besides, the error text is constantly visible at the top of the page, although I display all notifications using responseText(ajax request) and bootstrap toasts.

Source: Ask PHP

LEAVE A COMMENT