Anti CSRF Token – PHP
1. Add a unique token to the hidden field of user form on submit and store it on the session. Add the following codes to achieve this.
<?php $token = md5(uniqid(rand(), TRUE)); $_SESSION[“token_$token”] = time(); ?> <form action="login.php" method="post"> <input type="hidden" name="token" value="<?php echo $token; ?>" /> <p> Username: <input type="text" name="username" /><br /> Password: <input type="text" name="password" /><br /> <input type="submit" value="Login" /> </p> </form>
2. Before processing, validate the token on serverside.
<?php if (isset($_SESSION['token_' . $_POST['token']]) { // prevent use the token twice unset($_SESSION['token_' . $_POST['token']]); /* Valid Token */ } ?>
3. The validity of token can also be limited
<?php $token_age = time() - $_SESSION['token_time']; if ($token_age <= 600) { /* Less than ten minutes has passed. */ } ?>
Leave a Reply
Want to join the discussion?Feel free to contribute!