Search code examples
phpcsrf

CSRF code not working


I am reading a book "Essential PHP Security" by Chris Shifflet. There is a chapter on CSRF, where the author recommends using token to prevent CSRF. The code in the book says to add a token in a form we use

<?php

session_start();
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
$_SESSION['token_time'] = time();

?>

<form action="buy.php" method="POST">
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<p>
Item:
<select name="item">
    <option name="pen">pen</option>
    <option name="pencil">pencil</option>
</select><br />
Quantity: <input type="text" name="quantity" /><br />
<input type="submit" value="Buy" />
</p>
</form>

and the token can be checked with a simple conditional statement.

<?php

if (isset($_SESSION['token']) && $_POST['token']== $_SESSION['token'])
    {
        echo $_POST['token'];
        echo "form passed";
    }

But the above code does not seem to work. The "form passed" message does not shows. What is wrong with the above code?. The first set of codes generate the token but there isn't a success message.


Solution

  • You need to add session_start(); top of that codes in buy.php. Example...

    session_start();
    if (isset($_SESSION['token']) && $_POST['token']== $_SESSION['token'])
    {
        echo $_POST['token'];
        echo "form passed";
    }