The first thing we need to check is the user's captcha. Recaptcha developers suggest this validation script:
<?php require_once('recaptchalib.php'); $errors=array(); $privatekey = "***Add your recaptcha private key here***"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
die ("The reCAPTCHA wasn't entered correctly. Go back and try
"(reCAPTCHA said: " . $resp->error . ")");
}
However, instead of terminating the script with die (), we will assign errors to a PHP array named $errors[] . With this approach we can dump all errors back to the users (along with field name error validation, not only the captcha) at once. So instead of having the die() command, we will have this: if (!$resp->is_valid) { $errors[] = 'ERROR: The recaptcha code was not entered correctly or expired. If you think it expired or correctly entered; click Recaptcha refresh button <img src="/ajaxrecaptcha/getanewchallenge.jpg" /> to get a new challenge and press submit again.'; } If an error occurs, the text value error will be assigned to the array. The rest of the validation script follows the same principle as above. For example, in checking to see if the name, phone number and age fields are empty: if (empty($name)) { $errors[] = 'ERROR: The name field is empty.'; } if (empty($phonenumber)) { $errors[] = 'ERROR: The phone field is empty.'; } if (empty($age)) { $errors[] = 'ERROR: The age field is empty.'; }
In the last part of the series of validation scripts, you need to determine how many errors are detected by the entire validation script. If there is no error, then proceed with the rest of the form processing (for example, displaying info back to the user, adding input to the MySQL database, etc). This can be accomplished using the PHP function sizeof(), which will count the number of entries in the array. The script below does the actual work of dumping the errors back to the user: if (sizeof($errors) > 0) { echo "<ul>"; foreach ($errors as $e) { echo "<li>$e</li>"; } echo "</ul>"; die (); } This code will be inserted after validation scripts: <?php
/// Insert series of validation scripts here
if (sizeof($errors) > 0) { echo "<ul>"; foreach ($errors as $e) { echo "<li>$e</li>"; } echo "</ul>"; die (); } So for example, if mistakes are inputted in the form, it will display them all at once:
You can download the source code and see an actual working example.
blog comments powered by Disqus |
|
|
|
|
|
|
|