I want to generate Captcha Image using PHP imagettftext. And following is my code. It gives an empty image. I want to resolve this issue.
I have tested the code but was unable to find why the image is not bieng showed although my random text is being passed to the function of captcha image generation.
<?php
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
function generateCaptchaImage($text = 'good'){
echo $text;
echo 'OK';
// Set the content-type
header('Content-Type: image/png');
$width = 200;
$height = 30;
$font = 'ThisisKeSha.ttf';
// Create the image
$im = imagecreatetruecolor($width, $height);
//ADD NOISE - DRAW background squares
$square_count = 6;
for ($i = 0; $i < 10; $i++) {
$cx = (int)rand(0, $width/2);
$cy = (int)rand(0, $height);
$h = $cy + (int)rand(0, $height/5);
$w = $cx + (int)rand($width/3, $width);
imagefilledrectangle($im, $cx, $cy, $w, $h, $white);
}
//ADD NOISE - DRAW ELLIPSES
$ellipse_count = 5;
for ($i = 0; $i < $ellipse_count; $i++) {
$cx = (int)rand(-1*($width/2), $width + ($width/2));
$cy = (int)rand(-1*($height/2), $height + ($height/2));
$h = (int)rand($height/2, 2*$height);
$w = (int)rand($width/2, 2*$width);
imageellipse($im, $cx, $cy, $w, $h, $grey);
}
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
imagepng($im);
}
$randomString = generateRandomString();
generateCaptchaImage($randomString);
?>
It's a easy way to create captacha in PHP, You can try this,
php session used on this. Here is more details about Captcha in PHP
Try this code;
You didnt generated the colors
$white
,$black
and$grey
. Also the font must be there in the same folder of this php file.Nice Captcha image generator:
Solved from comments
$white
and$black
are not defined.echo $text;
andecho 'OK';
.ThisisKeSha.ttf
on your server and in the same directory as this?$white
and$black
were not defined.