【发布时间】:2011-11-29 06:15:04
【问题描述】:
我正在尝试创建验证码,但正在创建的代码未存储在会话变量中。这是我用来创建代码和存储值的文件。我的 php 页面上有一个 session_start(),它也会显示验证码。
<?php session_start();
class CaptchaSecurityImages {
var $font = './monofont.ttf';
function generateCode($characters) {
/* list all possible characters, similar looking characters and vowels have been removed */
$possible = '23456789bcdfghjkmnpqrstvwxyz';
$code = '';
$i = 0;
while ($i < $characters) {
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
return $code;
}
function CaptchaSecurityImages($width='120',$height='40',$characters='6') {
$code = $this->generateCode($characters);
/* font size will be 75% of the image height */
$_SESSION['security_code'] = $code;
$font_size = $height * 0.75;
$image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
/* set the colours */
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 20, 40, 100);
$noise_color = imagecolorallocate($image, 100, 120, 180);
/* generate random dots in background */
for( $i=0; $i<($width*$height)/3; $i++ ) {
imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
}
/* generate random lines in background */
for( $i=0; $i<($width*$height)/150; $i++ ) {
imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
}
/* create textbox and add text */
$textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
$x = ($width - $textbox[4])/2;
$y = ($height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
/* output captcha image to browser */
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
}
}
$width = isset($_GET['width']) ? $_GET['width'] : '120';
$height = isset($_GET['height']) ? $_GET['height'] : '40';
$characters = isset($_GET['characters']) && $_GET['characters'] > 1 ? $_GET['characters'] : '6';
$captcha = new CaptchaSecurityImages($width,$height,$characters);
?>
我可以在会话中存储其他项目并且它们工作得很好。我不确定为什么这个值不会存储。我发现了其他关于让验证码工作的帖子,但没有关于在会话中存储值的问题。有什么建议吗?
谢谢 罗伯特
【问题讨论】:
-
如果这是用于生产代码,您是否查看过reCAPTCHA?
-
我在我的一个网站上遇到了同样的问题,奇怪的是我已经在大约 10 个网站上运行它并且这个没有保存会话.. 你可以评论输出行 (header + imagejpg + imagedestroy) 和 print_r($_SESSION) 以查看它是否在运行文件时存储。
-
谢谢奥斯汀,我会调查的。这就是我遇到的 Pendo,我不确定这是否与为图像值设置标题或发生了什么有关,但它似乎很奇怪,它可以在某些地方工作,但不是这个。
-
可以添加你用来显示的代码吗?
-
这是我下载代码的 URL。即使使用下载中的确切文件也不起作用。 white-hat-web-design.co.uk/articles/php-captcha.php