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!
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:
Code for this form inside a html file would be:
We will save this file as test.html.
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(100, 999);
$_SESSION['check'] = ($number);
$white = imagecolorallocate($img, 255, 255, 255);
imagestring($img, 10, 8, 3, $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:
Now when we go to our test.html file it will look like this
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';
}
?>
We have prepared the files for download. Click here to download the whole package.
Hi and welcome to our site. More examples coming soon.