Simple PHP captcha

12.Aug.2010

In this snippet we show you how to create simple PHP captcha protection for your website forms.

In root of your domain create PHP file called captcha.php, and paste following snippet into it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
session_start();
 
$str = "";
$length = 0;
for ($i = 0; $i < 6; $i++) {
	// these numbers represent ASCII table (small letters)
	$str .= chr(rand(97, 122));
}
 
//md5 letters and saving them to session
$letters = md5($str);
$_SESSION['letters'] = $letters;
 
//determine width and height for our image and create it
$imgW = 300;
$imgH = 100;
$image = imagecreatetruecolor($imgW, $imgH);
 
//setup background color and border color
$backgr_col = imagecolorallocate($image, 238,239,239);
$border_col = imagecolorallocate($image, 208,208,208);
 
//let's choose color in range of purple color
$text_col = imagecolorallocate($image, rand(70,90),rand(50,70),rand(120,140));
 
//now fill rectangle and draw border
imagefilledrectangle($image, 0, 0, $imgW, $imgH, $backgr_col);
imagerectangle($image, 0, 0, $imgW-1, $imgH-1, $border_col);
 
//save fonts in same folder where you PHP captcha script is
//name these fonts by numbers from 1 to 3
//we shall choose different font each time
$fn = rand(1,3);
$font = $fn . ".ttf";
 
//setup captcha letter size and angle of captcha letters
$font_size = $imgH / 2.2;
$angle = rand(-15,15);
$box = imagettfbbox($font_size, $angle, $font, $str);
$x = (int)($imgW - $box[4]) / 2;
$y = (int)($imgH - $box[5]) / 2;
imagettftext($image, $font_size, $angle, $x, $y, $text_col, $font, $str);
 
//now we should output captcha image
header("Content-type: image/png");
imagepng($image);
imagedestroy ($image);

To use simple PHP captcha on your website form, simply output following snippet onto your HTML form:

<p>Insert letters from image below:</p>
<img src="http://yourdomain.com/captcha.php" width="300" height="100" alt="simple PHP captcha" />
<input type="text" name="captcha" />

In order to validate users input on your HTML form, use following PHP snippet:

1
2
3
4
5
6
7
8
session_start();
$is_valid = $_SESSION['letters'] == md5(strtolower($_POST['captcha']));
 
if (!$is_valid) {
	echo 'Letters from simple PHP captcha have not been entered correctly....';
} else {
	echo 'Letters from simple PHP captcha have been entered correctly.';
}

If you would like to see example of this form or just a captcha image, please checkout website where I used it.

1. Captcha image: http://interstan.com/captcha.php (you can refresh the page to see different presentation)
2. Simple PHP captcha used on web form: http://interstan.com/kontakt/prodajem-nekretnine-stan-kucu-lokal/