存储验证码的会话值


Storing Session values for captcha's

我正在尝试创建一个验证码代码,但正在创建的代码未存储在会话变量中。 这是我用来创建代码和存储值的文件。 我的 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 来完成这项任务。

如何将您的图像加载到用户的浏览器中? 它是否在同一个域上? 如果不是,则问题很可能是您的 cookie 被排除在外,因为它是"第三方 cookie"。 要让浏览器保存此 cookie,您必须设置 P3P 标头,以便浏览器知道可以保存 cookie。

有效 P3P 标头的示例如下:

header('P3P: CP="CAO PSA OUR"');

希望这有帮助。