0

I am building website in PHP. To every form tag I add token field to prevent CSRF attacks.

In each page I am creating a random string and store it in the session.

$_SESSION['form1_token'] = hash('sha512', uniqid(null, true));

HTML:

<form ...>
    <input type="hidden" value="<?php echo $_SESSION['form1_token']; ?>" />
    ....
</form>

Then I check the value in the server side and delete the token from the session.

It works fine, but what can I do if the user navigate to another page without sending the form? The token will never be deleted.

Time limitation is not good, because my web page supposed to run for a long time, and require refreshment could be annoying. So I thought about sending request in the unload event to delete the session. But users with a little bit knowledge in web, can with every browser to delete the event.

How can I manage the tokens correctly?

Gumbo
  • 643,351
  • 109
  • 780
  • 844
nrofis
  • 8,975
  • 14
  • 58
  • 113
  • 3
    Have a look at [CSRF protection: do we have to generate a token for every form?](http://stackoverflow.com/q/8655817/53114) – Gumbo Jun 09 '14 at 16:47

1 Answers1

0

Use a time limit. Set it to something long (like a day). If the page is designed to sit there for longer than that, then send an Ajax request on a timer to a script that extends the lifetime of the token in the database.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335