Basic CAPTCHA

Jan 04, 2010

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

<?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(); 
?>