我有一个验证码发生器php代码,它给出$_SESSION['captcha_string']
会话变量的值字符串。无法获得实际会话变量(HTML/PHP)
PHP验证码生成器代码:
<?php
session_start();
header ("Content-type: image/png");
$dirPath="/opt/lampp/htdocs/WebSiteFolder/dfxCaptcha/";
$font='/opt/lampp/htdocs/WebSiteFolder/DejaVuSerif-Bold.ttf';
$imgWidth=200;
$imgHeight=50;
global $image;
$image = imagecreatetruecolor($imgWidth, $imgHeight) or die("Cannot initialize a new GD image stream.");
$background_color = imagecolorallocate($image, 0, 0, 0);
$text_color = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, $imgWidth, $imgHeight, $background_color);
$letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$len = strlen($letters);
$letter = $letters[rand(0, $len - 1)];
$word = "";
for ($i = 0; $i < 4; $i++) {
$letter = $letters[rand(0, $len - 1)];
imagettftext($image, 15, 0, $i*50+25, 50, $text_color, $font, $letter);
$word .= $letter;
}
$_SESSION['captcha_string'] = $word;
$images = glob($dirPath."*.png");
foreach ($images as $image_to_delete) {
@unlink($image_to_delete);
}
imagepng($image);
?>
姑且,当我加载运行验证码生成器的页面,我尝试打印出来(见下面的代码)的$_SESSION['captcha_string']
变量的值,但它给出了以前生成的值(即:延迟)。例如,我加载页面,验证码图像显示“ABCDE”。我重新加载页面,验证码图像显示“BCDEF”,但打印值为“ABCDE”。之后,我重新加载页面,验证码图像显示“CDEFG”,打印值为“BCDEF”。
HTML代码:
<?php session_start(); ?>
<!DOCTYPE html>
.. some irrelevant code here ..
<img id="captchaimg" src="captcha_generator.php">
<div><?php echo $_SESSION['captcha_string'] ?></div>
我怎么能做到这一点吗?
更新:我如何才能实现图像和$_SESSION['captcha_string']
将在同一时间适当的对?其实我需要在javascript函数中使用ACTUAL$_SESSION['captcha_string']
。怎么样?
我完全不明白。执行的顺序不是与HTML中的代码顺序相同吗?首先生成验证码并设置会话变量,然后“打印”。 – ZsG
问题是:您是否在调用'captcha_generator.php'。浏览器在您发送完整页面并加载图像之后。 – colburton
因此,整个页面在发生器-php运行之前加载? – ZsG