Securimage and AJAX
Using Securimage PHP Captcha with AJAX
This is a beginner’s tutorial for creating an AJAX powered web form with CAPTCHA protection.
Processing forms with JavaScript and the XMLHttpRequest object (AJAX) not only make form processing easier in many situations, but when done correctly and also make for a good user experience. After reading this tutorial you should be able to set up a very basic AJAX contact form with CAPTCHA protection.
The comple source code for this example is available. Download Source
We will first begin with the HTML form that will be used for collecting the user’s information.
If you are brave you can try integrating the code directly into your existing form, or create a new HTML document with html, head, and body tags to use for the example and call it form.html.
<form id="contact_form" action="process.php" method="post" onsubmit="return processForm()">
<div style="float: left; width: 100px">Your name:</div>
<div style="float: left"><input type="text" name="sender_name" size="20" /></div>
<div style="clear: both"></div>
<div style="float: left; width: 100px">Email:</div>
<div style="float: left"><input type="text" name="sender_email" size="30" /></div>
<div style="clear: both"></div>
<div style="float: left; width: 100px">Message:</div>
<div style="float: left">
<textarea name="message" rows="4" cols="30"></textarea>
</div>
<div style="clear: both"></div>
<div style="float: left; width: 100px">Security Image:</div>
<div style="float: left"><img src="securimage/securimage_show.php" alt="CAPTCHA Image" /></div>
<div style="clear: both"></div>
<div style="float: left; width: 100px">Security Code:</div>
<div style="float: left"><input type="text" name="code" size="8" /></div>
<div style="clear: both"></div>
<div style="float: left; width: 100px"> </div>
<div style="float: left">
<input id="submit" type="submit" value="Send Message" />
</div>
<div style="clear: both"></div>
</form>
The form has an id contact_form which is used by JavaScript to access the form and its elements. We use the action to define what script the form data will be sent to and the method attribute to indicate a POST request. The onsubmit attribute is used to run the JS code within it when the user submits the form. A return value of false tells the browser to stop processing the form and not send the user to the URL in the action attribute.
Each of the form fields will be identified by it’s name and will be sent to PHP in the $_POST array. The div tags are only used for alignment and are unimportant for this example.
Now all that remains for the HTML page is the JavaScript that will make the AJAX request and handle the response. To simplify AJAX requests and accessing form elements, we will use the Prototype JavaScript Framework. This library will do most of the heavy lifting for us and even deal with a lot of the browser incompatibilities. A copy is included in the source of the example.
To use Prototype’s features, we only need to reference it via a script tag in the head of the document.
Place the following code into your <head> tag and put prototype.js in the folder with the HTML file.
<script type="text/javascript" src="prototype.js"></script>
Next we need to add the JavaScript that will get the form values and make the request to our form processor. Add this code within your <head> tag, below the prototype line added above.
<script type="text/javascript">
<!--
function processForm()
{
$('submit').disabled = true;
$('submit').value = "Processing. Please Wait...";
$('contact_form').request({
onSuccess: function(transport)
{
if(transport.responseText.match(/^OK/) != null) {
alert('Your message has been sent!');
$('contact_form').reset();
} else {
alert(transport.responseText);
}
$('submit').value = 'Send Message';
$('submit').disabled = false;
}
});
return false;
}
-->
</script>
Step-by-step explanation of JavaScript code Skip to PHP »
Define the JavaScript function that is used by the form’s onsubmit attribute.
function processForm()
Disable submit button to prevent user from clicking more than once, also change it’s text.
$('submit').disabled = true;
$('submit').value = "Processing. Please Wait...";
This line uses Prototype to create an AJAX request using the fields from contact_form
$('contact_form').request({ ... });
The onSuccess option passed to the request method is used to retrieve the response received by our AJAX request. We use it to pass a function that will be called by Prototype upon completion of the request. Prototype will also pass an object to the function which contains the response body.
We then check the response body to see if it begins with OK. We will use that in our form processor to indicate success. The processor will send back the error message to display if a field was not properly filled in.
Once we handle the response, the submit button is re-enabled and it’s text is replaced with the original value.
onSuccess: function(transport)
{
if(transport.responseText.match(/^OK/) != null) {
alert('Your message has been sent!');
$('contact_form').reset();
} else {
alert(transport.responseText);
}
$('submit').value = 'Send Message';
$('submit').disabled = false;
}
This is returned to the form telling the browser to not process it for us.
Since by default AJAX requests in prototype are asynchronous, this code is reached before the AJAX request is completed.
return false;
The PHP Form Processor
Now that all of our client side code is in place, we can move on to the PHP script that will act as our form processor and receive the form data sent by our AJAX request.
The form processor will contain some basic field validation and validate the CAPTCHA code entered was correct.
Copy the following code and place it in a file called process.php
<?php
$your_email = 'you@example.com';
if ($_SERVER['REQUEST_METHOD'] != 'POST') exit;
foreach($_POST as $key => $value) $_POST[$key] = urldecode(trim($value));
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['message'];
$code = $_POST['code'];
$errors = array();
if ($name == '') {
$errors[] = "Please enter your name";
}
if ($email == '') {
$errors[] = "Please enter your email address";
} else if (strpos($email, '@') === false) {
$errors[] = "Please enter a valid email address";
}
if ($message == '') {
$errors[] = "Please enter a message to send";
}
if (sizeof($errors) == 0) {
require_once 'securimage/securimage.php';
$img = new Securimage;
if ($img->check($code) == false) {
$errors[] = "Incorrect security code entered";
}
}
if (sizeof($errors) > 0) {
$str = implode("\n", $errors);
die("There was an error with your submission! Please correct the following:\n\n" . $str);
}
$time = date('r');
$body = <<<EOD
Hi!
A message was sent to you from $name on $time.
Here is their message:
$message
EOD;
mail($your_email,
"Contact Form Sent",
$body,
"From: $your_email\r\nReply-To: $email\r\nContent-Type: text/plain; charset=ISO-8859-1");
die('OK'); // send success indicator
?>
Detailed explanation of PHP Code. Skip to Summary »
Used later in the script to control where the form is emailed to. Change this to your email address.
$your_email = 'you@example.com';
Quit processing if the request is not from a form POST.
Decode values and trim unwanted whitespace from form fields.
if ($_SERVER['REQUEST_METHOD'] != 'POST') exit; foreach($_POST as $key => $value) $_POST[$key] = urldecode(trim($value));
Get each form field into a short variable. The $_POST value names come from the field names in the contact form.
$name = $_POST['sender_name']; $email = $_POST['sender_email']; $message = $_POST['message']; $code = $_POST['code'];
Create an array to store any error messages.
$errors = array();
Very basic field validation to check for blanks.
If a field is empty or invalid, we add an entry to the error array.
if ($name == '') {
$errors[] = "Please enter your name";
}
if ($email == '') {
$errors[] = "Please enter your email address";
} else if (strpos($email, '@') === false) {
$errors[] = "Please enter a valid email address";
}
if ($message == '') {
$errors[] = "Please enter a message to send";
}
This next section of code is what validates the CAPTCHA code entered.
We first include the securimage.php file and create a new Securimage object. (Note: The path may need to be changed depending on your directory structure.)
We only want to check the code if there are no errors present because when a correct code is verified with Securimage, it will delete the code so it cannot be re-used (and abused!) by a malicious user.
If the code entered is incorrect, the error is added to the error array.
if (sizeof($errors) == 0) {
require_once 'securimage/securimage.php';
$img = new Securimage;
if ($img->check($code) == false) {
$errors[] = "Incorrect security code entered";
}
}
Now check to see if there are any errors. If so, stop execution with die and output the error message.
if (sizeof($errors) > 0) {
$str = implode("\n", $errors);
die("There was an error with your submission! Please correct the following:\n\n" . $str);
}
Once this point is reached we know there are no errors and the CAPTCHA code was entered correctly so the form can safely be processed and sent.
PHP’s date function will get us the time the form was sent.
Then we create a variable called body and use the form variables to create the email message.
$time = date('r');
$body = <<<EOD
Hi!
A message was sent to you from $name on $time.
Here is their message:
$message
EOD;
We use PHP’s mail function to send the message to the email address indicated at the beginning of the script.
After the message is sent, we send the OK indicator back to the browser so our JavaScript knows everything was successful.
mail($your_email,
"Contact Form Sent",
$message,
"From: $your_email\r\nReply-To: $email\r\nContent-Type: text/plain; charset=ISO-8859-1");
die('OK');
Finishing Up
Now with all the necessary pieces in place, the form code and the PHP form processor should function together.
This is intended to be a simple demonstration of using CAPTCHA with AJAX and can be used as a building block for a more complex form. The overall process of validating a form with AJAX is simple and straightforward and easily extensible. I hope you found this tutorial useful.
If you encounter errors or some part of the script does not work, I encourage you to first try using the example project to see if that works. In order for the CAPTCHA to function, you should download Securimage and place it in a directory in the folder that has process.php.
Please post any questions or comments below.
Useful Links:
- Tutorial Source Code: Download the complete example for this tutorial
- Download Prototype: Get the latest version of Prototype
- Prototype Ajax Request Docs: Additional reference for using AJAX in Prototype.
- Introduction to JavaScript: A basic introduction to programming in JavaScript.
- PHP for the Absolute Beginner: Beginner’s tutorial on PHP programming.






