Basic CAPTCHA

Mon, Jan 4, 2010

PHP, Snippets

Very basic code demonstrating the use of the GD library by creating a simple CAPTCHA.

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
<?php
function randomString($length){
    $pattern = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    if(empty($length)){
        $length = "10";
    }

    for($i=0; $i<$length; $i++){
        $string .= $pattern{rand(0,61)};
    }

    return $string;
}

function captcha() {
    header("Content-type: image/png");
    $im = @imagecreate(100, 50) or die("Cannot Initialize new GD image stream");
    $background_color = imagecolorallocate($im, 0, 0, 0);
    $text_color = imagecolorallocate($im, 255, 0, 0);
    $string = randomString();
    imagestring($im, 10, 5, 5,  $string, $text_color);
    imagepng($im);
    imagedestroy($im);
}

captcha();
?>

Tags: , ,