2017-07-18 73 views
0

我有一个验证码发生器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']。怎么样?

回答

1

这部分表示您的浏览器加载后captcha_generator.php您将页面发送给它。

<img id="captchaimg" src="captcha_generator.php"> 
<div><?php echo $_SESSION['captcha_string'] ?></div> 

您正在为图像生成新的验证码。你需要改变这一点。

您可以在页面加载时生成新的验证码,并返回图像请求中以前生成的验证码。


如果您有可能避免这个问题captcha_generator.php回的图像内容,然后直接将其作为数据源:

<img id="captchaimg" src="data:image/png;base64,<?php echo base64_encode(include captcha_generator.php) ?>"> 
+0

我完全不明白。执行的顺序不是与HTML中的代码顺序相同吗?首先生成验证码并设置会话变量,然后“打印”。 – ZsG

+0

问题是:您是否在调用'captcha_generator.php'。浏览器在您发送完整页面并加载图像之后。 – colburton

+0

因此,整个页面在发生器-php运行之前加载? – ZsG