PHP Image Captcha Tutorial
  Jul 24, 2009

Unfortunately, spammers of all kinds continuously scan for pages that contain elements in which they, or their bots, can post their spam messages easily. Though the attacks can get sophisticated if they target your exact defense mechanism, you can easily circumvent many of the bots by using a simple captcha.

A captcha is just a method of getting the user to jump through a hoop of some sort to identify

Complete Code Dump

First, create a directory somewhere because we will need a populate it with few files to get a working captcha example. Read on and place the example code in their respective files. After we create all the example files, we should then be able to upload this directory to a PHP enabled webserver and view it with a browser.

captcha_img.php

I might come back and elaborate on this, but the comments are pretty self explanitory. Pretty much I generate an image $WIDTH wide and $HEIGHT high. I then add a random colored background with randomly created arcs and lines. I then add text, using a single for or a collection of fonts, with varying properties in appearance.

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/**************************************
 * Author:  Lyle Scott, III
 *          http://lylescott.ws
 *          http://digitalfoo.net
 *          lyle@digitalfoo.net
 * Created: May 15, 2009
 * Updated: July 17, 2009
 ***************************************/
 
$WIDTH  = 270;
$HEIGHT = 50;
 
/* Start the session to keep track of our original 
 * captcha code so we can later compare it to what 
 * the user enters on the following page.
 */
 
session_start();
 
// generate a random 32 character alpha numeric string
$md5 = md5(microtime() * mktime());
 
// take 5 characters
$md5_str = substr($md5, 5, 5);
 
$final_str = "";
// camel case it
for ($i = 0; $i < strlen($md5_str); $i++) {
    $char = substr($md5_str, $i, 1);
 
    if ((rand(0, 100) % 2) == 0) 
        $final_str .= strtoupper($char);
    else     
        $final_str .= strtolower($char);
}
 
// initialize blank image 
$image = imagecreate($WIDTH, $HEIGHT); 
 
// set the background color for the image
$color_bg = imagecolorallocate($image, rand(150, 255), rand(150, 255), rand(150, 255)); 
 
// generate randomly colored/positioned lines
for ($i = 0; $i < 18; $i++) {
 
    // generate random color
    $color_line = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
 
    // draw line with random points
    imageline($image, rand(0, imagesx($image)), 
                      rand(0, imagesy($image)), 
                      rand(0, imagesx($image)), 
                      rand(0, imagesy($image)), 
                      $color_line);
 
    if (($i % 2) == 0) {
        imagearc($image, rand(0, $WIDTH), rand(0, $HEIGHT), 
                         rand(100, $WIDTH), rand(100, $HEIGHT), 
                         rand(0, 180), rand(0, 180), 
                         $color_line);
    } 
}                      
 
// initial values for "drawing" our string values
$font_size = 24;
$x = -15;
$y = 40;
 
// generate random text.. in front of lines
for ($i = 0; $i < 5; $i++) {
 
    // random font color
    $color_fg = imagecolorallocate($image, rand(0, 100), rand(0, 100), rand(0, 100));
 
    // random angle to tilt character
    $angle = rand(-35, 35);                       
 
    // alter the X and Y coords slightly for each character
    $x += rand(25, 55);
    $y += rand(-3, 3);
 
    // grab each consecutive character during each iteration of our loop
    $char = substr($final_str, $i, 1);
 
    /*
    // random font selection... works but commented out
    // for simplicity
    $c = rand(1,3);
    switch ($c)
    {
        case 1: $font = "zektonbo.ttt";   break;
        case 2: $font = "GARABL.ttf";     break;
        case 3: $font = "SimpleLife.ttf"; break;
    }
    // the above is disabled, so static font :D 
    */
 
    // use this static font.. check out dafont.com for more
    $font = "SimpleLife.ttf";
 
    // draw string to image
    imagettftext($image, $font_size, $angle, $x, $y, $color_fg, $font, $char);
}                      
 
// save the captcha code
$_SESSION["captcha_key"] = $final_str;
 
header("Content-type: image/png");
imagepng($image);
imagedestroy($image);
 
?>

captcha_test.html

This is the code to demonstrate how you could set this up on aa page for real world use... as I do on a few sites! You should have enough code for a working example by the end of this code block.

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
<?php session_start(); ?>
<html>
<head>
  <script type="text/javascript">
      function refresh_captcha() {
          var r = Math.floor(Math.random() * 100);
          document.getElementById("captcha_img").src="captcha_img.php?" + r;
      }
  </script>
</head>
<body>
 
<h4>Captcha Demo</h4>
<a href="javascript:refresh_captcha();">
  <img src="refresh.png" alt="refresh captcha" style="border:none;">
</a>
 
<form action="" method="post">
<input type="text" maxlength="5" name="captcha_code">
<input type="submit" name="comment_submit" value="verify">
</form>
 
<br>
 
<h4>Result</h4>
<?php
if (isset($_POST["captcha_code"]) 
        && strcmp($_POST["captcha_code"], $_SESSION["captcha_key"]) == 0)
    echo "<strong>Success!</strong>";
else
    echo "Not verified...";
?>
 
</body>
</html>

Miscellaneous Files

I have provided the miscellaneous files I use with my captcha as well as an entire archive of a working example with the code already spelled out for you in case you had problems along the way.






Post a New Comment

Name

Message

Security
Code

        (case insensitive & space between words)


Posted Comments
anonymous  Aug 10, 2011
iphone 4 unlock how to unlock iphone 4 unlock iphone 4 http://www.cdapress.com/news/local_news/article_16a1f630-1d3d-5efa-bb19-182b6ab81170.html http://www.libgig.com/node/1721 I have Kaspersky Anti-Virus and I've just received a message that a trojan is loading (something like that)...when I opened kaspersky protection state it says: status -infected, Trojan program.TrojanJSagent.axt and the location is the website I visited. What to do now, how to remove infection (because the field remove is disabled for some reason). Please help? <a href="http://unlockiphone44.com">unlock iphone 4</a> unlock iphone 4 unlock iphone 4 <a href=http://unlockiphone44.com>iphone 4 unlock</a> unlock iphone 4 unlock iphone 4