'PHP: $_SESSION not populating from include

right off the bat: yes. i know to set session_start() at the top of each file except includes. so let's get that out of the way.

i've written a little captcha that works on it's own but when it is 'included' in the parent page, the $_SESSION doesn't tranfer. it's empty.

the file structure/relationship looks like this:

  parent page  <-- has session_start()
       ^
  captcha form  <-- no session_start()
       ^
  captcha generator  <-- has session_start()

so if i run the captcha form itself, the varibles work fine and the captcha works. but when i include it in the parent page, there is no $_SESSION.

i'm not sure what code to include here since, technically, all the pieces work... but here's what i think the relevant snippets are:

parent page

if (empty($_POST["captcha_input"])) {
  $captchaERR = "CAPTCHA MUST BE COMPLETED";
} else {
  $captcha_input = test_input($_POST["captcha_input"]);
  consolelog('captcha_input: '.$captcha_input);
  consolelog('captcha_text: '.$_SESSION['captcha_text']);
  if (!preg_match("/^[a-zA-Z0-9 ]*$/",$captcha_input)) {
    $captchaERR = "CAPTCHA FAILED. Letters & Numbers ONLY.";
  } elseif ($_POST['captcha_input'] == $_SESSION['captcha_text']){
    $readySetGO .= 'GO';  //  progression string
  } else {
    $captchaERR = "CAPTCHA FAILED.";
  }
}

//  this is where the form gets loaded or the success page.
if ($readySetGO === "readySetGO") {
  mail($to, $subject, $message, $headers);
  session_destroy();
  include('assets/php/success.php');
} else {
  include('assets/php/contactForm.php');  //  aka 'captcha form'

  // consolelog('-----------------------------------------------');
  consolelog('dumping $_SESSION variable...');
  var_dump($_SESSION);
}

captcha form (contactForm.php)

<br>  <!--  Captcha  ------------------------------------->
<div id="captcha">
  <img class="captcha" src="./captcha/CaptchaImageGenerator.php" />
  <p class="captcha-input">          
    <input name="captcha_input" type="text" class="feedback-input" placeholder=" Enter Captcha here" /><span class="error"><?php echo $captchaERR; ?></span>
  </p>
</div>
<br>  <!--  end of Captcha  ------------------------------>

captcha generator

//  generator code not included because they work and aren't relevant
$result = new CaptchaImageGenerator();
$text = $result->generateCaptchaText();
$_SESSION['captcha_text'] = $text;
$result->getCaptcha($text);

to state once again: the session_start() is at the VERY top of the relevant pages (as indicated above). and the code works when just running the captcha form itself. it just stops when it gets included in the parent page.

please help me get it working. i don't know what i'm missing.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source