PHP - Simple PHP captcha script

A very basic PHP / GD based captcha script for stopping those spammers from flooding your guestbooks, mailforms or any other online application susceptible to spam spawning web bots.spam

You can also download the captcha script here

Requires only PHP with GD library installation and a true type font file(.ttf) to create the image

First you make the actual captcha image generating file, and save it as (for instance) 'captcha.php':

To see an example of this script in a live site - have a look at this guestbook. Or just leave a comment below this article

	// generate random number and store in session
	$randomnr = rand(1000, 9999);
	$_SESSION['randomnr2'] = md5($randomnr);
	//generate image
	$im = imagecreatetruecolor(100, 38);
	$white = imagecolorallocate($im, 255, 255, 255);
	$grey = imagecolorallocate($im, 128, 128, 128);
	$black = imagecolorallocate($im, 0, 0, 0);
	imagefilledrectangle($im, 0, 0, 200, 35, $black);
	//path to font:
	$font = '/var/www/font.ttf';
	//draw text:
	imagettftext($im, 35, 0, 22, 24, $grey, $font, $randomnr);
	imagettftext($im, 35, 0, 15, 26, $white, $font, $randomnr);
	// prevent client side  caching
	header("Expires: Wed, 1 Jan 1997 00:00:00 GMT");
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
	header("Cache-Control: no-store, no-cache, must-revalidate");
	header("Cache-Control: post-check=0, pre-check=0", false);
	header("Pragma: no-cache");
	//send image to browser
	header ("Content-type: image/gif");

this is an exampe of a form containing the captcha image file captcha.php:

	<title>html form with php captcha</title>
	<form method="post" action="write.php">
		<input class="input" type="text" name="norobot" />
		<img src="captcha.php" />
		<input type="submit" value="Submit" />

Now all we need is a serverside file that processes the values sent by this form and checks if the captcha test was passed succesfully. In the form above this is refered to by the attribute "action=write.php" and it should contain code something similar to the following:

	if (md5($_POST['norobot']) == $_SESSION['randomnr2'])	{ 
		// here you  place code to be executed if the captcha test passes
			echo "Hey great , it appears you are not a robot";
	}	else {  
		// here you  place code to be executed if the captcha test fails
			echo "you're a very naughty robot!";
very nice.
I m very new to php.

I use this but captcha not showing image?

Thx in Advance

I agree, simple scripts and easy to adjust, a good starting point.

Thanks for the post.
Can somebody tell me whats wrong with my php code? (write.php)

header("Content-Type: text/html; charset=ISO-8859-9");
if (md5($_POST['norobot']) == $_SESSION['randomnr2']) {

$field_name = $_POST['field_name'];
$field_email = $_POST['field_email'];
$field_tel = $_POST['field_tel'];
$field_message = $_POST['field_message'];
$radio_button = $_POST['radio_button'];
$drop_down_item = $_POST['drop_down_item'];

$mail_to = '';
$subject = 'contact form: '.$drop_down_item;

$body_message = 'Full Name '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Telephone: '.$field_tel."\n";
$body_message .= "Feedback: ".$radio_button."\n";
$body_message .= 'Message: '.$field_message;

$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";

$mail_status = mail($mail_to, $subject, $body_message, $headers);

if ($mail_status) { ?>

else { ?>


else {
echo "wrong code!";


waiting for comment and is my e-mail.
Simples e bem feito
ten times
Many thanks webmaster. It was easy to setup and implement in my site. Recommended. I\'m using it in many of my pages.
Great script... Just follow the instruction, abracadabra you're form have a captcha...

Great script, Thank you!

U vulde in:

Achternaam: " . $naam . "
Achternaam: U heeft geen naam ingevuld!
Email: " . $email . "
Email: Vul een geldig email adres in!
Bericht: " . $reactie . "
Bericht: U heeft niets ingevuld bij bericht!

//Was alles correct ingevuld?
//maak een verbinding met de database
$link = mysql_connect($mysql_host, $mysql_user, $mysql_pass);
//selecteer de juiste database
mysql_select_db("reacties", $link);

//kijk of een persoon al bestaat
$sql = "SELECT id FROM personen WHERE naam = '" . $naam . "' AND email = '" . $email . "'";
//echo $sql . "
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0){
//vraag de id van een bestaand persoon op
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$persoon_id = $row['id'];
} else {
//voeg de naam en email toe in de tabel personen
$sql = "INSERT INTO personen(naam, email) VALUES ('" . $naam . "', '" . $email . "')";
//echo $sql . "
//vraag de id van de nieuwe persoon op
$persoon_id = mysql_insert_id();

//voeg de reactie toe in de tabel reacties. Gebruik de id van de zojuist toegevoegde persoon
$sql = "INSERT INTO reacties(persoon_id, reactie, datum) VALUES (" . $persoon_id . ", '" . $reactie . "', NOW())";
//echo $sql . "

//sluit de database
echo "

Bovenstaande informatie is opgeslagen!
echo "

Er is een foute waarde ingevoerd, ga terug.
if (md5($_POST['norobot']) == $_SESSION['randomnr2'])
// here you place code to be executed if the captcha test passes
echo "de code is juist ingevuld";
} else {
// here you place code to be executed if the captcha test fails
echo "U heeft een verkeerde code ingevuld!";
yes it works
Do not forget following:
after checking the Captcha input.

Amazing website!
nice work!
Thanks for the script fella.
Very easy to implement too, excellent.

Implemented it on the comment form at the bottom of this page:

I've added a credit at the bottom of the form linking back to here too.
First of all - thanks ever o much for kindly sharing this script. It\'s awesome. I\'m a beginner/n00b php user however and I\'m having a little bit of difficulty modifying this to fit into another piece of php that I want to use. Instead of saying \"if \'norobot\' is equal to \'randomnr2\' ... echo \"great\" I want to do the reverse. I want to say this ... \"if \'norobot\' is NOT equal to \"randomnr2\" display $error \"message\" in a
Cool en doeltreffend! Kun je wel uitleggen waarom je session_start aanroept in write.php? In captcha.php zelf snap ik het wel...
omdat je $_SESSION['randomnr2']) , uit de sessie global nodig hebt.
Finally a SIMPLE and clear captcha which you can work on without wasting time. Really a good job. Thanks!
Thanks very much for the script.
It helped me a lot.

And how can we add a background image?

Thanks again
It's quite easy to do all sorts of adjustments. have a look at the gd library reference for php
rendered @ Wed Apr 23 12:57:12 CEST 2014