I read about CSFR, it is not clear why this code does not work:

<? session_start(); $_SESSION["sid"] = md5(time() . rand(0, 10000)); ?> <!DOCTYPE html> <html> <head> <title>FORM</title> </head> <body> <div id="wrap"> <form action="" method="POST"> <input type="hidden" id="sid" name="sid" value="<?= $_SESSION["sid"]; ?>"> <textarea cols="50" name="msg" rows="10"></textarea> <br> <input type="submit" name="sub" value="Send"> </form> </div> </body> <script type="text/javascript"> </script> <? if(isset($_POST["sub"])) { if(isset($_POST["sid"]) && $_POST["sid"]==$_SESSION["sid"]{ $_SESSION["sid"]="" ; echo "SUCCESS!"; } else { echo "ERROR!"; } } ?> </html> 

gives ERROR, it is clear that the page reloads .. but then how to do it right? the name "sid" = "token" . Never mind

    3 answers 3

    You generate a CSRF token (which was called sid for some reason) every time. Of course, they will never be equal.

    There are 2 ways to solve the problem:

    1. Install a CSRF token after all the content has been generated, but before it is sent. Not an approach in your case, since you have HTML code interspersed with php-inserts. If you used, say, a template engine, this approach might look like this:

       session_start(); $response = generate_body(); // тут происходит вся обработка // тут можно выставить какие-нибудь заголовки $_SESSION["sid"] = md5(time() . rand(0, 10000)); echo $response 
    2. Remember the previous value of the token and compare with it.

       $previous_token = $_SESSION["sid"] 

      $ _SESSION ["sid"] is not the same as $ _SESSION ["sid"]

      Up

       <? session_start(); if (!isset($_POST["sub"])) $_SESSION["sid"] = md5(time() . rand(0, 10000)); ?> 
      • corrected. but that's not the problem - cmd
      • Completed the answer. In your case, the variable in the session is overwritten each time, and you are comparing the new value with the old one. I checked it myself, it works. It is also worth checking in the lower checks the presence of all the brackets ... - Caravus

      Do you have a SID generation done? just the session always has a SID, the native function of getting it session_id

      There is no need to memorize anything just in the html in the right place, insert session_id and compare with it.