开发者

Session variable always a page load behind in php?

I'm using the following code to create a captcha on my site, but when I try to read the value back from the session, it is always the previous captcha value.

<?php

session_sta开发者_如何学Pythonrt();

$captchaStr = md5(microtime() * mktime());
$captchaStr = substr($captchaStr,0,5);

$_SESSION["captcha"] = $captchaStr;

$captcha = imagecreatefrompng("../images/captcha.png");
$black = imagecolorallocate($captcha, 154, 32, 242);
$line = imagecolorallocate($captcha, 233, 239, 239);

// Draw lines
imageline($captcha, 0, 0, 39, 29, $line);
imageline($captcha, 40, 0, 64, 29, $line);

// Add captcha text
imagestring($captcha, 5, 20, 10, $_SESSION["captcha"], $black);

header("Content-type: image/png");
imagepng($captcha);

?>

Does anyone have any ideas why this is and how to fix it?

Cheers


I'm guessing you're trying to read back the captcha value from the page that contains the captcha value, something like this:

<?php session_start(); ?>

<img src="/lib/captcha.php" />

<?php echo "Captcha is: ", $_SESSION['captcha'] ?>

This would never work. PHP locks the session file by default, so your captcha script can not run until the above container page completes execution. As well, since the captcha is being fetched as a seperate call, the user's browser has to initiate a call back to the server to fetch the image. This will take on the order of seconds to complete, while the container page will be done within microseconds.

In other words, the captcha generator script will very likely NEVER start running until after the container script has completed, which means the container script will never see the new captcha string in the session file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜