Return to Snippet

Revision: 32841
at October 3, 2010 04:45 by mikael12


Initial Code
<?php

function create_captcha($char_count = 6)
{
	$possible = '23456789bcdfghjkmnpqrstvwxyz';
	$security_code = '';
	$i = 0;
	while ($i < $char_count) {
		$security_code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
		$i++;
	}

    //Set the session to store the security code
    $_SESSION["captcha_code"] = $security_code;

    $width = 100;
    $height = 25;

    //Create the image resource
    $image = ImageCreate($width, $height);

    //We are making three colors, white, black and gray
    $white = ImageColorAllocate($image, 255, 255, 255);
    $black = ImageColorAllocate($image, 0, 0, 0);
    $grey = ImageColorAllocate($image, 204, 204, 204);

    //Make the background black
    ImageFill($image, 0, 0, $black);

    //Add randomly generated string in white to the image
    ImageString($image, 5, 30, 3, $security_code, $white);

    //Throw in some lines to make it a little bit harder for any bots to break
    ImageRectangle($image,0,0,$width-1,$height-1,$grey);
    imageline($image, 0, 5, $width, 5, $grey);
    imageline($image, $width/4, 0, $width/2, $height, $grey);
    imageline($image, 0, 18, $width, 18, $grey);
    imageline($image, 46, 0, 86, $height, $grey);

    header("Content-Type: image/jpeg");

    //Output the newly created image in jpeg format
    ImageJpeg($image);

    //Free up resources
    ImageDestroy($image);
}

create_captcha();

?>

Initial URL

                                

Initial Description
In img tag set src=\"captcha.php\"

Initial Title
Simple image CAPTCHA

Initial Tags

                                

Initial Language
PHP