Home
Examples
Under construction.

Captcha tutorial in PHP

What is captcha?

An anti-spam form protection image written in PHP. For this captcha tutorial we need a form (plain html file), one PHP file which will generate a picture and a session and one PHP file which will check the result. Let's get started!

1. Form, a plain html file - test.html

First, we create a simple html file with a form inside and one field in it called check which would then be similar to this:

Form

Code for this form inside a html file would be:

<form method="POST" action="checkit.php">
<img src="captcha.php"> <br>
<input type="text" size="10" name="check"> <br>
<input type="submit" name="submit" value="Submit">
</form>

We will save this file as test.html.

2. PHP file that creates a captcha - captcha.php

Now we will create a PHP file that creates an image/captcha and we will call it captcha.php. Source code for this file is:

<?php session_start();
$img imagecreatefrompng('background.png');
$number rand(100999);
$_SESSION['check'] = ($number);
$white imagecolorallocate($img255255255);
imagestring($img1083$number$white);
header ("Content-type: image/png"); imagepng($img);
?> 

This code sets the random number between 100 and 999, assigns its value to the session called check and draws white numbers using 'background.png' for a background image. This creates our captcha. Background image is for example:

Background

Now when we go to our test.html file it will look like this

Captcha2

3. PHP file that validates the captcha - checkit.php

This PHP file validates the user input. When user hits the Submit button, this file will check the captcha. Code:

<?php 
session_start
();
if((
$_POST['check']) == $_SESSION['check']) { 
echo 
'Input OK';
}else{ 
echo 
'Input Wrong';        
}
?> 

4. Download all files

We have prepared the files for download. Click here to download the whole package.

User comments:

Rawn

Posted on 28. January 2010.

Hi and welcome to our site. More examples coming soon.

Leave your comment:
Name:
Email (optional):
Comment:
 
Security code: