I'm using $_SESSION
to store data from a multi-page form. Everything was working wonderfully until I finished a submission and ended the session to prevent the same form data being replicated should the person try to re-enter the form. When the form is complete and submitted, kill the session and erase session data:
$_SESSION = array();
setcookie(session_name(), '', time() - 42000);
session_destroy();
What follows is this:
<?php
session_start();
include "connect-moo.php";
$learning = true;
//get any post variables and save them to the session
foreach ($_POST as $key => $val) {
$_SESSION[$key] = $val;
}
sessionDump(); //dumps session to db
//check to see if step is set (in the post eg ?step=getaquote). If not, set it to current session step
if(!isset($_POST["step"])) {
if(isset($_SESSION['step'])) {
$_POST['step'] = $_SESSION['step'];
}
}
//show the page appropriate to the current step
if ($_SESSION['mode'] == 'edit' && $_SESSION['lastpage'] != "review" && $_SESSION['step'] != "session") {
$_SESSION['lastpage'] = 'review';
getReview();
}
else {
if($_SESSION['step'] != 'session') $_SESSION['lastpage'] = $_SESSION['step'];
switch ($_POST["step"])
{
case "session":
foreach($_SESSION as $key => $val){
echo $key.": ".$val."<br>";
//phpinfo();
}
echo "Post Data<br>";
foreach($_POST as $key => $val) {
$sval = mysql_real_escape_string($val);
$skey = mysql_real_escape_string($key);
echo $skey.": ".$sval."<br>";
}
break;
case "getaquote":
getAQuote();
break;
// and so on...
default:
start();
}
}
... (all of the abovementioned functions)
?>
I have confirmed that a new session cookie is being established but $_POST
and $_SESSION
are empty after restarting the session. With the recent fix (thanks!) I can push data into the $_POST and $_SESION arrays programatically (e.g. $_POST['foo'] = 'bar';) but variables passed through the URI are ignored.
Solutions:
re session_destroy, see Alex B answer.
re. the $_POST issue - it turns out that, when entering the information via URL directly, the server was interpreting it(correctly) as a GET not a POST. I amended my code to grab all GET & POST data but will only need POST in production. Here's the new code:
//get any submitted variables and save them to the session
foreach ($_GET as $key => $val) {
$_SESSION[$key] = $val;
}
foreach ($_POST as $key => $val) {
$_SESSION[$key] = $val;
}