Using Recaptcha in AJAX Prototype Framework with PHP

One of the biggest problems with form handling is spam. If the form is not protected with captcha, then most likely spam and auto-form submission will happen. But thanks to Google Recaptcha, PHP and AJAX technology, a webmaster can now implement captcha protection without severely affecting the user’s experience. This is a beginner tutorial on using Recaptcha with the AJAX prototype framework and PHP.

AJAX is highly beneficial to speed up the browsing experience because your pages will not need to be reloaded to process form results as well as implement user validation.

The HTML Web Form (index.php)

A sample web form protected with Recaptcha and AJAX Prototype Framework using PHP validation is here: http://www.php-developer.org/recaptchaajaxprototype/

It is a very simple web form that asks for the user’s age; after form submission, it can tell whether the visitor is a minor or a senior citizen.

To check whether the form user is a human, recaptcha is used. Below is the form’s HTML code:

<body>
<h3>Form protected with Recaptcha using AJAX Prototype Framework</h3>
<form action="/recaptchaajaxprototype/recaptchavalidate.php" method="post" onsubmit="return false;">
Enter your age<br />
<input style="background-color: #FFFFC0" name="age" id="age" size="15">
<br /><br />
<?php
require_once(‘recaptchalib.php’);
$publickey = "YOUR RECAPTCHA PUBLIC KEY";
echo recaptcha_get_html($publickey);
?>
<input type="submit" value="Submit" onClick="sendRequest()">
</form>
<br />
Your age verification will be shown below:
<br />
<p class="yellow" id="show"></p>
<br />
</body>


Note that the form action URL is the recaptcha validation script. Recaptcha uses POST to submit variables to the script. A detailed discussion of this script will be provided later.

The actual captcha that is visible on the browser is generated by this PHP code:

<?php
require_once(‘recaptchalib.php’);
$publickey = "YOUR RECAPTCHA PUBLIC KEY";
echo recaptcha_get_html($publickey);
?>

You can get your own recaptcha public key here: http://www.google.com/recaptcha

The form input should use the id property. In this example, the id is set to “age.” This is needed during an AJAX request.

The result/output of the form handling validation and inquiry will be shown in this line of HTML:

<p class="yellow" id="show"></p>

Results from the server side processing will be communicated through AJAX and outputted to the HTML using the id property. In that case, id is set to “show.”

The AJAX request will start after the user clicks the submit button. AJAX request functions are contained in a JavaScript function named sendRequest(), discussed below.

sendRequest() AJAX request function in index.php

The AJAX functions are contained in the JavaScript section of index.php. Mostly, these are found in the <head> section of the code.

First, at the top of the <head> section, the external reference to the Prototype JavaScript framework is added:

<script type="text/javascript" src="prototype.js"></script>

Then AJAX processing takes the following steps (right after the form is submitted for validation):

Step 1. The onclick event function sendRequest() will be triggered after clicking the submit form.

Step 2. Initiate a new AJAX request inside the sendRequest() function to validate the user’s Recaptcha answer. The Recaptcha user’s answer is posted to the validating script: recaptchavalidate.php.

This is done by passing the values from the web form to the AJAX request parameters. Once the recaptcha validation has been completed on recaptchavalidate.php, the output text is then assigned to the “EvaluateResponse” Javascript function.

The code: 

function sendRequest() {

//Iniate AJAX request using POST to recaptcha validation script recaptchavalidate.php

new Ajax.Request("/recaptchaajaxprototype/recaptchavalidate.php",
{
method: ‘post’,

//Pass the user answer obtained from the web form to AJAX Request parameters.
 
parameters: ‘recaptcha_challenge_field=’+$F(‘recaptcha_challenge_field’)+’&recaptcha_response_field=’+$F(‘recaptcha_response_field’),

//Assign the text output results of recaptchavalidate.php script to EvaluateResponse function
//There is only one possible text output posted back if the Recaptcha validation fails. The text value “Wrong” is outputted.
//Otherwise if the recaptcha validation succeeds, it will pass the success validation key using PHP sessions. More on this will be discussed later on.

onComplete: EvaluateResponse
});
}

EvaluateResponse(req) JavaScript Function in index.php

Step3.) Below is the EvaluateResponse(req) JavaScript function:

function EvaluateResponse(req){

//Assign the text output from recaptcha validation script to response variable

var response = req.responseText;

//Assign text to variables to be used for conditional evaluation.

var wrong = "Wrong";
var compare ="Incorrect captcha";

//Check if the recaptcha validation did not succeed, such as wrong user captcha entry.

if (response==wrong) {

//If the validation did not succeed, alert the user that the captcha entry is incorrect.

alert(compare);

//Refresh the Recaptcha and present another challenge to the user

Recaptcha.reload();
}
else {

//The recaptcha validation is correct, pass the validation success value to processdata() JavaScript function.

processdata();
}
}

processdata() AJAX request function in index.php

Step 4. This function only works when the Recaptcha validation is a success. When the captcha validation succeeds, the user data (age for example) will be posted to process.php for processing. Below is the processdata() AJAX request function:

function processdata() {

//Create a new Ajax request. Post the age values from the web form the AJAX request parameters to process.php

new Ajax.Request("/recaptchaajaxprototype/process.php",
{
method: ‘post’,

parameters: ‘age=’+$F(‘age’),

//Upon completion of the form data processing, output the results back to the user
//The output will be shown using showResponse JavaScript function.

onComplete: showResponse
});
}

Step 5. Below is the showResponse(req) function:

function showResponse(req){

//Assign the AJAX response text output coming from process.php to HTML.
//This will output the results to an HTML element that uses “show” id. Refer to HTML form discussion in the previous section.

$(‘show’).innerHTML= req.responseText;

//After showing the result back to the web browser, reload or refresh the recaptcha.
//This is important so that succeeding entries are validated to be coming from human, not from a bot.

Recaptcha.reload();
}

{mospagebreak title=The Final Functions}

The Final AJAX/JavaScript Functions in Index.php <head>

<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
function sendRequest() {
new Ajax.Request("/recaptchaajaxprototype/recaptchavalidate.php",
{
method: ‘post’,
parameters: ‘recaptcha_challenge_field=’+$F(‘recaptcha_challenge_field’)+’&recaptcha_response_field=’+$F(‘recaptcha_response_field’),
onComplete: EvaluateResponse
});
}
function EvaluateResponse(req){
var response = req.responseText;
var wrong = "Wrong";
var compare ="Incorrect captcha";
if (response==wrong) {
alert(compare);
Recaptcha.reload();
}
else {
processdata();
}
}
function processdata() {
//Server side validation and form processing
new Ajax.Request("/recaptchaajaxprototype/process.php",
{
method: ‘post’,
parameters: ‘age=’+$F(‘age’),
onComplete: showResponse
});
}
function showResponse(req){
$(‘show’).innerHTML= req.responseText;
Recaptcha.reload();
}
</script>

RecaptchaValidate.php Script

This PHP script is used by the AJAX function to validate the user’s Recaptcha input. The following is the code:

<?php

//Start PHP session
//Session is used to pass the success validation key to the process.php script, indicating that the Recaptcha validation has been successful.

//Session is a safe way to pass the values because the success validation value will not be visible using a client browser.

session_start();

//Require the recaptcha library files.

require_once(‘recaptchalib.php’);

//Define your own Recaptcha private key here.

$privatekey = "YOUR RECAPTCHA PRIVATE KEY HERE";

//Post the recaptcha answer to server for comparison.

$resp = recaptcha_check_answer ($privatekey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]);

//Check if the user recaptcha answer is correct or not.

if (!$resp->is_valid)

//If the answer is incorrect, then output the text “Wrong”. This text value will be assigned to AJAX req.responseText and will be used by the Javascript functions to do comparison.
{
echo "Wrong";
}
if ($resp->is_valid)
{

//If the Recaptcha answer is valid, then assign the MD5 value of the Recaptcha private key to a session variable.

//This session variable will be passed to process.php web forms for Recaptcha success validation.

//For security reasons, session are used instead of passing the values back to the AJAX and Javascript functions.

//It is because if the values are passed back to JavaScript, it will be accessible by the client browser and can compromise the key.

$_SESSION['validatesuccess']= md5($privatekey);
}
?>

Process.php Script

This PHP script will do the work of form processing. It will retrieve the form’s user inputs, process them and send output back to the user. However, it will only accept and process form values if the Recaptcha validation succeeds.

<?php

//Start the PHP session, this is REQUIRED to retrieve the success validation key values passed from Recaptchavalidate.php

session_start();


//Assign all errors to an array

$errors=array();

//Your Recaptcha private key

$privatekey = "YOUR RECAPTCHA PRIVATE KEY HERE";

//MD5 again your private in process.php so that the hash value will be compared to the value from the recaptchavalidate.php

$hash=md5($privatekey);

//Assign the value of the session coming from recaptchavalidate.php to a php variable.

$recaptchavalidation = $_SESSION['validatesuccess'];

//Check if the captcha is correct by comparing the hashed value to the value from the session variable

if ($recaptchavalidation <> $hash)
{
$errors[]= "ERROR: Wrong Recaptcha.";
}

//Start of actual form handling. Retrieving the posted values from the web form and other processing. You can replace the entire PHP code below with your own application.

$age =trim($_POST['age']);
if (empty($age)) {
$errors[] = ‘ERROR: Your age is empty.';
}

if (!(is_numeric($age))) {
//not a number
$errors[] = ‘ERROR: The submitted data is NOT a NUMBER';
}
$roundup= round($age);
$inttest= abs($roundup-$age);
if ($inttest !=0) {
//not an integer
$errors[] = ‘ERROR: The submitted data is NOT an INTEGER. Only non-decimal values are allowed.';
}

if (($age < 0) || ($age == 0)) {

//less than

$errors[] = ‘ERROR: Negative number is NOT allowed.';

}

if (sizeof($errors) > 0)
{
 echo "<ul>";
 foreach ($errors as $e)
 {
  echo "<li>$e</li>";
 }
 echo "</ul>";
 die ();
}
//data submitted by user are valid, determine age criteria
if ($age<18) {
 echo ‘You are a minor!';
}
if (($age>17) && ($age<60)) {
    echo ‘Your age belongs to the majority!';
}
if ($age>59) {
    echo ‘You are a senior citizen!';
}

//End of Form processing
//Destroy the session value.

session_destroy();
?>

You can download all of thee project scripts here: http://www.php-developer.org/recaptchaajaxprototype/

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye