简体   繁体   中英

I can't figure out why my PHP Session variables are being overwritten on page redirect

I have a page using session variables that are created from user form input via the POST method. The session variables are being created properly using this code:

(I am collecting a zip code via an input on a form)

<form name="zipinput" id="zipform" method="post" action="" target="_blank" onsubmit="return valZip();"/>     
 <input id="zip" name="zip" class="zipfield" type="text" value="" />
 </form> 

Here is my PHP code:

$_SESSION['zip'] = $_POST['zip'];
if(isset($_SESSION['zip'])) {
$zipcode = $_SESSION['zip'];
}

This works fine. But when I go from page1.php to page2.php, the variables are erased. I thought the whole point of session variables was to be able to use them from page to page without _GET or _POST in the URL. I am also including: session_start(); at the top of my php pages.

Any ideas would be greatly appreciated. Thanks.

That's because you're assigning a value to the session whether or not a zip value was actually provided. If not zip parameter is presesnt, you just write in a blank, which erases the previous zip. You'd want to do:

if (isset($_POST['zip'])) {
   $_SESSION['zip'] = $_POST['zip'];
}
$zip = $_SESSION['zip'];
if(isset($_POST['zip'])
$_SESSION['zip'] = $_POST['zip'];
if(isset($_SESSION['zip'])) {
$zipcode = $_SESSION['zip'];
}

instead of just having session_start() at the top of the page, try having

if(!isset($_SESSION)):
    session_start();
endif;

You must start a session on all pages. This is a good candidate for being put in an init file to arbitrarily be loaded in all pages before any other page content.. like in the header.

If you don't, the session you saved will be destroyed upon page redirect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM