Here I will be explaining how to use one use tokens, the tutorial will be in the form of using them to prevent muiltiple submits, such as when a user refreshes the page on a form!
Well, here we go!
With single use form tokens we can prevent mistakes such as when a user refreshes a page, it will send the POST data of a register, process, download etc. again. It can be also be freely used to allow any download link to be used once as well.
What we do to define a unique token ID is with uniqid():
<?php
// start session
session_start();
// create unique token
$form_token = uniqid();
// commit token to session
$_SESSION['user_token'] = $form_token;
?>Now within the <form> elements, all you need to add is a single field:<input type="hidden" name="user_token" value="<?php echo $_SESSION['user_token']; ?>" />All is good! What this does is, it will tell the client's browser to send the session token along with other POST elements. When the next page processes it, it can see if the token belongs to that form, so it cannot be accidentally resubmited as a new session token is generated each time.
Here is what we put in the POST processing page, another simple piece of code:
//We check if the token of the page and session match!
if($_POST['user_token'] == $_SESSION['user_token']) {
$message = 'Your download is <a href="foobar.xls"> Here </a> ';
} else {
$message = 'Your request has expired, please go back and resubmit!';
}
echo "We say: " . $message;
echo 'This is the <b>download page!</b> If you have successfully downloaded, please go to the instructions page or ask at our forum! (etc, etc)';
// invalidate the token so it expires on view, important!
unset($_SESSION['user_token']);
Always make sure you unset it and that is it. A few lines of code and you can make your application secure from double submits and the user hitting back for whatever reason!
So you heard it can be used for one time downloads.. You want to do it by URL instead of POST element? Oh? Well I have just the thing!
All you will need to do is replace the POST processing form part of the code with this:
if($_GET['sessid'] == $_SESSION['user_token']) {
...
And simply called by something such as this:
mypage.php?sessid=ab919108g2984fhu20
Generate the session token and sessid part of the url on the page where the download link will go.
Good luck, and safe coding.
Edited by Alexander, 11 October 2010 - 10:45 PM.
Updated to a new revision!


Sign In
Create Account

Back to top










