Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » php » PHP Based CAPTCHA Using Simple Math

PHP Based CAPTCHA Using Simple Math

Using PHP to create a CAPTCHA based on simple math.

View an Example of this article before you get started.

Spam is of course a huge issue when you allow visitors to post content or send messages from your website. The normal process is to use an image based CAPTCHA but sometimes your visitors will have trouble reading them and end up stopping valid people from posting. Another option is to use a simplified option, such as an easy question or request.

In this tutorial you will learn how to create a simple PHP based math CAPTCHA solution. This of course should not be a substitution for more complicated image based CAPTCHA, but can be used on smaller sites or less trafficked ones. Also be sure to use proper security (never accept user input without checking it). In this example the only security is the verification question, none of the input is checked.

Okay, lets start by creating a new PHP file. The entire script (example) will be in one file.

Creating the HTML form

Once the file is created start by adding the HTML form code

<form name="contact" action="" method="post">
	<p><h3>Name</h3><input type="text" name="in_name" value="<?=$name?>" /></p>
	<p><h3>Email</h3><input type="text" name="in_email" value="<?=$email?>" /></p>
	<p><h3>Message</h3><textarea name="in_msg" cols="40" rows="8"><?=$msg?></textarea></p>
	<p>
		<span<?=($fail_challenge)?" style=\"color:#ff0000;font-weight:bold;\"":""?>>
		Are you a human?</span>
		<br />What does 2 + 4 equal? <input type="text" name="in_challenge" />
	</p>
	<p><input type="submit" name="submit" value="Submit Information!" />
	<br /><small>(No message is really sent, this is a demo)</small></p>
</form>

As you'll notice there is a little PHP included in this form. To maintain form data (on reload) each form field will be assigned to a variable, which can be seen in each form field line, such as $name and so on. The final bit of PHP in the form code will be used to change the question to red if its wrong, to help the user.

For an added level of help to the user let's add a warning message to the top of the form code that will be displayed if the question is not answered or answered incorrectly.

<?php if($fail_challenge) { ?>
	
	<div style="width:400px;padding:5px;background-color:#cccccc;border:1px solid #ff0000;">
		<p>Incorrect or empty challenge answer!<br />Are you sure 
		you're not a robot? Try again!</p>
	</div>
	
<? } ?>

<form>
...

Before starting on the PHP code there is one final thing to add to the form portion of the code. Place the following IF statement around the verification warning and form code to make sure the form isn't displayed once its submitted.

<?php if(!$sent) { ?>

...
<form>
...

<? } ?>

Creating the PHP script

Now that the HTML form is completed let's start on the PHP code. The first part is to define the variables for the script, such as the question answer and values passed in from the form.

define("CHALLENGE_ANSWER", "6");

$name = isset($_POST['in_name']) ? $_POST['in_name'] : "";
$email = isset($_POST['in_email']) ? $_POST['in_email'] : "";
$msg = isset($_POST['in_msg']) ? $_POST['in_msg'] : "";
$challenge = isset($_POST['in_challenge']) ? $_POST['in_challenge'] : "";
$fail_challenge = false;
$sent = false;

One portion you may not be familiar with is the isset() inline. This is used to verify each field has been properly passed and if its not than the value is set to nothing. If you were to simply use $_POST['value'] and the value wasn't properly passed you would receive an error or in this case the value attribute of the text box would be invalid. The last part of the code above is a few simple boolean values to be used in the IF statements.

Wrapping up the script

The final portion of the PHP code is used to verify if the form values should be processed in more specific to this example the verification question is validated. If the form is passed AND the verification passes than a message is displayed to the user that the form would have been sent at this point. This is the portion where you could run your own custom code to send an email or query a database.

if(isset($_POST['submit']))
{	
	// check question
	if(empty($challenge) || (int) $challenge != CHALLENGE_ANSWER)
	{
		$fail_challenge = true;
	}
	else
	{
		print "<h2>Message sent! Thanks.</h2><p>Well not really sent.. 
		this is a demo! :)</p><p><a href=\"\">Send another?</a></p>";
		$sent = true;
	}
}

That's the complete script, here is the code in its entirety for you to quickly copy/paste.

<?php

/*
	Scriptplayground
	http://v2.scriptplayground.com
	
	THIS SOFTWARE IS PROVIDED BY SCRIPTPLAYGROUND "AS IS" AND ANY EXPRESS 
	OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
	WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
	ARE DISCLAIMED. IN NO EVENT SHALL SCRIPTPLAYGROUND OR CONTRIBUTORS BE 
	LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
	CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
	BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
	WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
	OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
	EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

define("CHALLENGE_ANSWER", "6");

$name = isset($_POST['in_name']) ? $_POST['in_name'] : "";
$email = isset($_POST['in_email']) ? $_POST['in_email'] : "";
$msg = isset($_POST['in_msg']) ? $_POST['in_msg'] : "";
$challenge = isset($_POST['in_challenge']) ? $_POST['in_challenge'] : "";
$fail_challenge = false;
$sent = false;

if(isset($_POST['submit']))
{	
	// check question
	if(empty($challenge) || (int) $challenge != CHALLENGE_ANSWER)
	{
		$fail_challenge = true;
	}
	else
	{
		print "<h2>Message sent! Thanks.</h2><p>Well not really sent.. 
		this is a demo! :)</p><p><a href=\"\">Send another?</a></p>";
		$sent = true;
	}
}

?>

<?php if(!$sent) { ?>

<?php if($fail_challenge) { ?>
	
	<div style="width:400px;padding:5px;background-color:#cccccc;border:1px solid #ff0000;">
		<p>Incorrect or empty challenge answer!<br />Are you sure 
		you're not a robot? Try again!</p>
	</div>
	
<? } ?>

<form name="contact" action="" method="post">
	<p><h3>Name</h3><input type="text" name="in_name" value="<?=$name?>" /></p>
	<p><h3>Email</h3><input type="text" name="in_email" value="<?=$email?>" /></p>
	<p><h3>Message</h3><textarea name="in_msg" cols="40" rows="8"><?=$msg?></textarea></p>
	<p>
		<span<?=($fail_challenge)?" style=\"color:#ff0000;font-weight:bold;\"":""?>>
		Are you a human?</span>
		<br />What does 2 + 4 equal? <input type="text" name="in_challenge" />
	</p>
	<p><input type="submit" name="submit" value="Submit Information!" /><br />
	<small>(No message is really sent, this is a demo)</small></p>
</form>

<? } ?>

Hopefully this has displayed some concepts that you can use in your own projects. As always be sure to post comments and questions below and happy scripting!

Follow Scriptplayground on Twitter (@scriptplay)

Comments: PHP Based CAPTCHA Using Simple Math

 sdf  Fri Feb 3, 2012 12:41 am  
sdfsdf
Add a comment
The ability to add new comments has been disabled in this archived version.

Loading
Main | Tutorials | Articles