2

I'm writing a site in PHP. And I have a simple registration form.

<form>
<label...></label> <input .../>
</form>

I want to add a confirmation field:

<input type='hidden' name='hiddeninput' value="jn3kjnv3kjvn35">

But how does this code look on the server side? Do I need to save every hidden value to the database whenever registration form is loaded?

I'm trying to make sure the form is not being filled in by bots.

That's why I need a random hidden value that is unique for every form submission.

Suppose every time I generate the registration page - I generate the unique value for "hidden" field.

When the user submits the form - how do I compare the submitted value to the one that was generated (as once it's generated - it's not stored anywhere in the site).

2
  • You need to give the hidden fields names too. Commented Mar 9, 2012 at 20:56
  • "Do I need to save every hidden value to the database whenever registration form is loaded?" - That depends on what you're trying to accomplish. Commented Mar 9, 2012 at 20:58

3 Answers 3

1

Basicly , you should use a function that generates a random string (hash for example) and sessions to "remember" this string. Aftet submitting the form , you'll check the INPUT's value and cross it with the SESSION's value.

For instance:

Form.php

<?php
 $hash = md5(time());
 $_SESSION['form_xx'] = $hash; //in case you have more than one form.
?>
<form method='post' action='do.php'>
..
..
<input type='hidden' name='secret_key' value='<?=$hash?>'>
</form>

do.php

if($_POST['secret_key'] == $_SESSION['form_xx']) //Just make sure your making the posted value SAFE
 //He's ok.
else
 die("arggg...those hackers");
Sign up to request clarification or add additional context in comments.

Comments

0

You need to add a name to the field, too. It works like pretty much any other HTML field.

Comments

0

I now use Ruby on Rails framework that solves it out of the box.

2 Comments

This is not an answer. Even if you start using a different framework unless you'll update your question it's not appropriate behaviour to mark an already accepted answer as not and accept your own answer.
Well, I wish when I looked for an answer, someone actually told me about Ruby on Rails. Because of answers like yours, I spent a lot of time reading books about every possible framework until I finally found Rails. More importantly, your answer doesn't follow MVC convention. So... Yeah. I think when people read this question it's more of a use for them to know they could switch to Rails than follow your answer and try to reinvent the wheel and manually create CSRF tokens.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.