Session variable cannot be set

I wrote a page ‘captcha.php’ to generate a math captcha and send the result through session to the page which request it.

In captcha.php:


$_SESSION['captcha'] = $var;//$var is the calculate result

In index.php:


<img src="/captcha.php"/><input id="captchaa" type="text" name="a"/>

...

<?php    

if($_POST['a']==$_SESSION['captcha'])

...

But I got ‘Undefined index: captcha’ error.

Any hint? Or what else more information do you need?

By the way, I’ve already included those lines in each file:


if(!isset($_SESSION))

{

    session_start();

}

First of all I would try to use Yii’s Session implementation, that could make things a lot easier:

http://www.yiiframework.com/doc/api/1.1/CHttpSession

Maybe it solves your issue

you have to import captcha.php.

require(‘path/to/captcha.php’);

That’s impossible to require or include that file because it should be output with a header specify it’s a jpeg file like


	

	header("Content-type:image/jpeg");

	

	header("Content-Disposition:inline ; filename=secure.jpg");

	

	imagejpeg($img);

I think i found the reason. My index.php is in the frame of Yii, and it has a session with id, but the captcha.php is not within the framework, so they cannot share a session.I tried to make it a view(/validation/captcha ),but it won’t work that way, don’t know why.

Now the problem is how to use Yii session in captcha.php.

If it it isn’t important to use a math captcha you could use Yii’s builtin in captcha http://www.yiiframework.com/doc/api/1.1/CCaptcha/.

If it is important than looking at the source code above still could help you to create your own widget. (http://www.yiiframework.com/doc/api/1.1/CCaptchaAction - look at sessionKey). I am pretty sure you could easily change the logic of Yiis Captcha to show some calculations.

In fact changing CCaptchaAction’s generateVerifyCode() method should be enough.

Hi,

try appending your session to captcha.php query string




<img src="/captcha.php?<?php echo Yii::app()->getSession()->getSessionName(); ?>=<?php echo Yii::app()->getSession()->getSessionID(); ?>"/><input id="captchaa" type="text" name="a"/>



why don’t you want to extend CCaptcha and CCaptchaAction?