Luke
Luke

Reputation: 544

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_start();

$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

Upvotes: 1

Views: 864

Answers (1)

Marc B
Marc B

Reputation: 360602

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.

Upvotes: 3

Related Questions