Ed Booth
Ed Booth

Reputation: 163

How to add security to a php form

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.

Upvotes: 0

Views: 323

Answers (1)

Remko
Remko

Reputation: 958

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!");
}
?>

Upvotes: 1

Related Questions