Home » Php » Displaying session array variable values displays on one page but not another – php

Displaying session array variable values displays on one page but not another – php

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a form on page5_form.php:

<form action="page6_form.php" method="post">
<input class="chk" id="check1" type="checkbox" name="infoCollectedAndSold[]" value="Identifiers">Identifiers<br>
            <input class="chk" type="checkbox" name="infoCollectedAndSold[]" value="Collect">
            <input class="chk" type="checkbox" name="infoCollectedAndSold[]" value="Sell">
           <input class="chk" id="disclosed" type="checkbox" name="infoCollectedAndSold[]" value="Disclose"><br><br>
<input type="submit" value="Next" />
</form>

The form inputs are stored in session variable like so:

<?php
session_start();
foreach ($_POST as $key => $value) {
    $_SESSION[$key] = $value;
}
?>

Then on another page called page6_form.php I display the values chosen from that form:

<?php
session_start();
$arr = $_POST['infoCollectedAndSold'];
foreach ($arr as $key => $val) {
   echo '<b>' . $val . '</b>';
}
?>

I then do the same exact thing on page7_form.php:

<?php
session_start();
$arr = $_POST['infoCollectedAndSold'];
foreach ($arr as $key => $val) {
   echo '<b>' . $val . '</b>';
}
?>

but get the error message:

Notice: Undefined index: infoCollectedAndSold in C:\xampp\htdocs\legalForm\page7_form.php
How to&Answers:

Could you provide some extra details about your use case, as the question title is misleading.
You are definitely not having a sessions issue as you title suggestion since you’re never trying to display session information on different pages.

In one case (page5_form.php) you have a form, that points to page6_form.php
you are also setting some data in session (also in page5_form.php – can you confirm that, as that’s suggested but not explicitely mentioned).

On page6_form.php, the target of the form displayed on page5_form.php, you simply echo data from $_POST.

On page7_form.php, you also output data from $_POST.

  1. you’re never outputting data from $_SESSION
  2. both page6 and page7 scripts only output data that’s sent via POST to them. It’s clear which form sends data to page6_form.php but not sure who sends data to page7_form.php, however assuming you just switch targets on the form displayed in page5_form.php, both page6 and page7 should display the same output assuming you’re selecting the same things in the form.

Cheers!