PHP Form
Free PHP forms, scripts, resources and tutorials.


Math Captcha

Published: 03/03/10


Creating a Math CAPTCHA with PHP :: PHP Tutorial

- Download source code (tutorial) - Math Captcha Script
- Requirement(s): PHP Server

This tutorial will show you how to create a form with Math Captcha.

1. Sessions in PHP are started by using the session_start() function. Like the setcookie( ) function, the session_start( ) function must come before any HTML, including blank lines, on the page.

Code:
<?php session_start(); ?>

2. Imagecreatefrompng :: create a new image from file or URL.

Code:
$img = imagecreatefrompng('black.png'); 

3. The function imagecolorallocate creates a color using RGB (red,green,blue) format.

Code:
$white = imagecolorallocate($img, 255, 255, 255); 

4. Displaying the random text on the captcha image.

Code:
//value 1
$numeroa = rand(1, 9);
//value2
$numerob = rand(1, 9);
$numero = $numeroa + $numerob;
$display = $numeroa . '+' . $numerob;

5. Check if the security code and the session value are not blank and if the input text matches the stored text.

Code:
if(($_POST['check']) == $_SESSION['check']) 
{ echo 'Input OK';
}else{ 
echo 'Input Wrong';        
}

Files



black.png


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

captcha.php:
<?php session_start(); 
$img imagecreatefrompng('black.png'); 
//value 1
$numeroa rand(19);
//value2
$numerob rand(19);
$numero $numeroa $numerob;
$display $numeroa '+' $numerob;
$_SESSION['check'] = $numero
//The function imagecolorallocate creates a 
//color using RGB (red,green,blue) format.
$white imagecolorallocate($img255255255); 
imagestring($img1083$display$white);
 
header ("Content-type: image/png"); imagepng($img); 
?>

cc.php:
<?php
session_start
(); 
//Sessions in PHP are started by using the 
//session_start() function.  
//Like the setcookie( ) function, 
//the session_start function must come before any HTML, 
//including blank lines, on the page.session_start(); 
//Check if the security code and 
//the session value are not blank 
//and if the input text matches the stored text
if(($_POST['check']) == $_SESSION['check']) { 
echo 
'Input OK';
}else{ 
echo 
'Input Wrong';        
}

example 1

example 2

Comments


Add a Comment

Name:


Comment:




Sitemap