php captcha session doesn't update

纵饮孤独 提交于 2020-01-15 07:26:06

问题


I have this code:

captcha.php:

session_start();
class Captcha {
    protected $code;
    protected $width = 35;
    protected $height = 150;

    function __construct() { 
        $this->code = substr(sha1(mt_rand()), 17, 6); 
        $_SESSION['captcha'] = $this->code;
    }

    function getCode(){
        return $this->code;
    }

    function showImage() {
             // here comes the code that builds the image.
             // it works fine!

    }
}


$image = new Captcha();

$image->showImage();

And in my login form I have:

<iframe src="includes/captcha.php" frameborder="0" height="65" width="180"></iframe>

if I print_r($_SESSION), the $_SESSION['captcha'] always in delay : it contains the previous captcha code , and not the current which is being shown.

What should I do?


回答1:


<iframe src="includes/captcha.php" frameborder="0" height="65" width="180"></iframe>

should be:

<img src='includes/captcha.php' style='height:65px;width:180px' />

As you should be loading the image as an image not as an iframe.

Also your CAPTCHA code if printed out on the parent page will always be the old value, as the new value only gets written when captcha.php is loaded which has happened after the main page has loaded so the new session value was not available at that time. So everything otherwise is working fine.




回答2:


It is due to the browser's cache so you have to do something like:

<iframe src="includes/captcha.php?<?php echo microtime();?>" 
frameborder="0" height="65" width="180"></iframe>


来源:https://stackoverflow.com/questions/14172760/php-captcha-session-doesnt-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!