Skip to content
Advertisement

Strange thing with PHP token confirmation

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.

Advertisement

Answer

The problem was solved by adding a check for the existence of $request.

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

}else{

      echo "Token confirmation error!";

    };
  };

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement