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?