我正在尝试为验证码制作一个简单的PHP脚本,但我不知道为什么它没有显示验证码图像。
这是脚本: `
<?php
session_start();
header("Content-Type: image/png");
$im = imagecreate(110, 20) or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
$possible_no="abcdefghjkmnpqrstuvwxyz23456789,@$";
$len=strlen($possible_no);
$random=mt_rand(0,$len);
$i=0;
while($i<=6){
$captcha .=substr($possible_no, mt_rand(0, strlen($possible_no)-1), 1);
$i++;
}
$a="$captcha";
imagestring($im, 1, 5, 5,"$a", $text_color);
imagepng($im);
imagedestroy($im);
$_SESSION['captcha']=$a;
?>`
提前感谢:)
答案 0 :(得分:1)
创建一个新文件(security_image.php)并将其放入其中: 也许你可能希望它以不同的方式显示,但你必须调整你想要的东西。
session_start();
function generate_code(){
$length = '6';
$chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '2', '3', '4', '5', '6', '7', '8', '9', ',', '@', '$');
$code = '';
for ($i=0; $i < $length; $i++){
$code .= $chars[rand(0, count($chars)-1)];
}
$_SESSION['captcha'] = $code;
return $code;
}
function security_image(){
$code = isset($_SESSION['captcha']) ? $_SESSION['captcha'] : generate_code();
$font = 'content/fonts/comic.ttf';
$width = '110';
$height = '20';
$font_size = $height * 0.75;
$image = @imagecreate($width, $height) or die('GD not installed');
$background_color = imagecolorallocate($image, 0, 0, 0);
$text_color = imagecolorallocate($image, 233, 14, 91);
$textbox = imagettfbbox($font_size, 0, $font, $code);
$x = ($width - $textbox[4]) / 2;
$y = ($height - $textbox[5]) / 2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
}
security_image();
然后在你的图片html标签中输入:
<img src="security_image.php" alt="security code" />
一旦你完成了你的过程之后设置:
unset($_SESSION['captcha']); // To reset the captcha
希望它有所帮助。你应该真正做到这一点,通过更改security_image()函数中的$code
var来重新生成你可以做的事情。