ISSUE :
 
Profile photo
Submitted by G-Stone
on June 6th, 2011 at 07:53:19 EST

how to generate captcha image on the fly in PHP?

Hi, I am trying to implement captcha for our website using php. For this, I am trying to generate random image on the fly. Can anyone please guide what could be the best way to create image on the fly in php with random text.
Thanks in advance.


Profile photo
Replied by SBajra
on June 6th, 2011 at 22:30:49 EST
To create image on the fly for the purpose of captcha: you can first generate random number then store the random number in the session and then generate the image with random number. To generate image on the fly, you can use php image functions.

Sample code:
function CreateSecurityImage($sessionName) 
{
//Generate random number
$text = rand();

//Set random number in session
SetSessionValue($sessionName, $text);

//Set the image width and height
$width = 130;
$height = 50;

//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, $grey);

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

//Tell the browser what kind of file is come in
header("Content-Type: image/jpeg");

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

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

Profile photo
Replied by Michael Gardnar
on June 6th, 2011 at 22:47:57 EST
I am also looking for this code. Cool !

Profile photo
Replied by G-Stone
on June 6th, 2011 at 22:48:51 EST
Thanks.