Quick Tip 1 - Secure your forms against CSRF attacks

Status
Not open for further replies.

Baljeet

Member
Jan 31, 2011
76
0
Read more about this type of attacks in .

In short, we want to ensure that the form data is coming from our website.

We start by generating a token for the hidden field of the HTML form. Then we will validate the submitted form token against the token that we've set in the session.


PHP:
<?php
session_start();
session_regenerate_id(true);

if (isset($_POST['submit'])) {

    if (isset($_SESSION['token']) && ($_POST['token'] == $_SESSION['token'])) {
        //token is ok, process data
    }

}

$token = hash('sha256', uniqid(mt_rand(), true));
$_SESSION['token'] = $token;

?>

HTML:
    <form method="POST" action="page.php">
        <input type="hidden" name="token" value="<?php echo $token; ?>">
        username: <input type="text" name="username">
        password: <input type="password" name="password" >
        <input type="submit" name="submit">
    </form>

All Credits goes to one who really made this...
 
Status
Not open for further replies.

Users who are viewing this thread

Top