dotslashlu
dotslashlu

Reputation: 3401

PHP - 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?

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.php.

Upvotes: 0

Views: 5422

Answers (5)

J0HN
J0HN

Reputation: 26941

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.

Upvotes: 1

heximal
heximal

Reputation: 10517

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.

Upvotes: 0

Jonnix
Jonnix

Reputation: 4187

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.

Upvotes: 0

Stefan H Singer
Stefan H Singer

Reputation: 5504

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

Upvotes: 0

mishu
mishu

Reputation: 5397

did you use the session_start function in both your files?

Upvotes: 2

Related Questions