0

I may be going about this the wrong way. I have a php form that collects information. After submitting it displays the information for verification. Then when you submit the form it send to another php script for processing.

I want to add a token/key that gets passed from the form to the verify form to make sure both are still on my site and then from the verify form to the final php script for processing.

This looked like the answer: How do I provide more security for checking source of the request

But I can't get it to work and I don't have enough reputation to comment. So out of pure frustration I am posting i here as a duplicate with my question.

The answer says to use this in the form:

<?php
    session_start();
    $csrfToken = md5(uniqid(mt_rand(),true)); // Token generation updated, as suggested by The Rook. Thanks!

    $_SESSION['csrfToken'] = $token;
?>
<form action="formHandler.php">
   <input type="hidden" name="csrfKey" value="<?php echo $csrfToken ?>" />
</form>

An this in the form handler:

<?php
   session_start();
   if($_POST['csrfKey'] != $_SESSION['csrfKey']) {
      die("Unauthorized source!");
   }
?>

It doesn't work. My question is shouldn't $_SESSION['csrfToken'] = $token; be $_SESSION['csrfToken'] = $csfrToken;

and shouldn't if($_POST['csrfKey'] != $_SESSION['csrfKey']) be if($_POST['csrfKey'] != $_SESSION['csrfToken'])

Although I've tried that and it doesn't work either.

I'm at a complete loss.

Community
  • 1
  • 1
Ed Booth
  • 163
  • 2
  • 13
  • Yes, those look like typos. After the corrections, what exactly 'doesn't work'? – santosh.ankr Jul 24 '13 at 19:37
  • It was a combination of those typos and my use of the echo in the hidden input field needed special formatting in my forms case. Thanks for validating that my thinking was correct though. – Ed Booth Jul 24 '13 at 22:26

1 Answers1

1

Cleaned up the typos and name-mixing, should work like this:

<?php
session_start();
$csrfToken = md5(uniqid(mt_rand(),true));
$_SESSION['csrfToken'] = $csrfToken;
?>
<form action="formHandler.php">
<input type="hidden" name="csrfToken" value="<?php echo $csrfToken?>" />
</form>

And than when validating the submitted data:

<?php
session_start();
if($_POST['csrfToken'] != $_SESSION['csrfToken']) {
  die("Unauthorized source!");
}
?>
Remko
  • 968
  • 6
  • 19