There are more ways of doing this. One of them is to use a captcha (a small text shown in an image that the user has to fill in the form). Here’s a tutorial on how to use one of these.
I will show you another way of doing this: having the user fill in the result of a mathematical operation. If the correct result is filled in, the form is sent to you.
You can see a demo of this on my website.
Here’s how we’ll do this:
Suppose we have the following contact form (in the file named contact.php):
<form action="send.php" id="contact" name="contact" method="post” <table align=left> <tr> <td>Name:</td> <td><input type="text" id="name" name="name"></td> </tr> <tr> <td>Email:</td> <td><input type="text" id="email" name="email"></td> </tr> <tr> <td>Message:</td> <td><textarea rows="5" cols="40" id = 'message' name = 'message'></textarea></td> </tr> <tr> <td><input type="submit" value="Send message"></td> </tr> </table> </form>
When the user presses the submit button, the send.php script will be called. This script sends an email with the info that was filled in the form.
We will have to add the part to verify the user.
We will ask the user to fill in the result of a mathematical operation. The user will have to add the randomly generated numbers between 1 and 15.
Here’s the code to generate the two numbers and compute the correct sum:
<?php srand(time()); $nr1 = (rand()%14)+1; $nr2 = (rand()%14)+1; $sum = $nr1 + $nr2; ?>
We will now display the numbers to the user and ask him/her to fill in the result in a new input field.
We’ll add a new row in the table which holds the form:
<tr> <td>Are you human?<br/>What is the result of <?php echo $nr1;?>+<?php echo $nr2;?>?</td> <td><input type="text" id="nr" name="nr"></td> </tr>
We’ll also add a hidden field to the form to hold the correct sum.
<input name="sum" id="sum" type="hidden" value="<?php echo $sum;?>"/>
These are all the changes we have to make to the contact form.
We’ll also have to modify the send.php script to check the sum before sending the email:
$nr = $_POST[nr];
$sum = $_POST[sum];
if ($nr != $sum)
header('Location: contact.php?msg=wrong');
else
// add code to send the mail with the form data
If the sum from the hidden field is equal to the one filled in by the user, the email is sent. If not, the user is redirected to the contact.php page and an error message is shown. Here’s what we’ll have to add to the contact.php file to show the error message:
if(isset($_GET['msg']))
{
if ($_GET['msg'] == 'wrong')
echo "<p> <font color=red>The result you entered is wrong!</font>";
}
And that’s it!
Let me know if you have questions or comments!






MultiQuote






|