开发者

PHP - session variable cannot be set

开发者 https://www.devze.com 2023-04-03 13:44 出处:网络
I wrote a page \'captcha.php\' to generate a math captcha and send the result through session to the page which request it.

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?

UPDATE: these lines are in both files if(!isset($_SESSION)) { session_start(); }

UPDATE: 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 generate image properly that way, don't know why.

Now the problem is how to use Yii's session in captcha.开发者_如何学JAVAphp.


did you use the session_start function in both your files?


It's because captcha.php is processed in a separate request by browser. So, the flow is the following:

  1. PHP executes index.php file. NO $_SESSION['captcha'] is set, so nothing is outputted
  2. PHP flushes the content to the browser.
  3. Browser sees src parameter of the img and loades that url
  4. PHP executes captcha.php and sets $_SESSION['captcha'], but the page is already rendered.

So, actually your $_SESSION['captcha'] is set after the index.php is processed and even after another HTTP request.

As a workaround you may use AJAX loading captcha, passing both captcha value and image via AJAX request and than injecting them into HTML page.


Hard to tell without seeing the rest of captcha.php, have you called session_start() before setting the session variable?


The variable $_SESSION['captcha'] will not be available in index.php until the next page load as it is being created in a request after the one you are currently in, if that make sense.

Checking if the form has been submitted /then/ checking the value against the $_SESSION should work as long as session_start() is being used correctly.


I agree with mishu about session_start. 'Undefined index: captcha' is not an error. It's rather a warning. If you don't suppress the output of warning messages, you should check if specified array index really exists:

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

to suppress warnings output you should use error_reportning function, if it's not critical to you.

0

精彩评论

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

关注公众号