简体   繁体   中英

Why does my session resets when I add value in 2nd page then go back to original one?

So I have 2 pages. On 1st one I start a session array. Then I redirect to 2nd page. There I add a value to session array. But When I go back to 1st page session array resets to 0 values. I did put session_start() at the begining of both pages.

page 1

<?php

session_start();
$shopping_cart = array();
$_SESSION['cart'] = $shopping_cart;



print_r($_SESSION['cart']);
#Array ( ) 
?>

page 2

<?php

session_start();
array_push($_SESSION['cart'], "test");
print_r($_SESSION['cart']);
#Array ([0] => test) 
?>

Think about this logically. Lets remove the complication of the real SESSION and fake it for demo purposes

In page 1 you do

$shopping_cart = array();
$SES['cart'] = $shopping_cart;
print_r($SES);

OUTPUT

Array
(
    [cart] => Array
        (
        )

)

In page 2 you do

array_push($SES['cart'], "test");
print_r($SES);

OUTPUT

Array
(
    [cart] => Array
        (
            [0] => test
        )

)

Then you go back to Page 1 and DESTROY what was in the session by re-initializing it to a blank array

$shopping_cart = array();
$SES['cart'] = $shopping_cart;
print_r($SES);

OUTPUT

Array
(
    [cart] => Array
        (
        )

)

Now if you had first checked if it was a good idea to re-initialise the session first, like this

$shopping_cart = array();
if ( !isset($SES['cart']) ) {
    $SES['cart'] = $shopping_cart;
}

print_r($SES);

You would get output like

Array
(
    [cart] => Array
        (
            [0] => test
        )

)

which would contain the data created in page2

You are overwriting the $_Session superglobal every time the first page loads. Use:

<?php
    session_start();
    if (!isset($_SESSION['cart'])) {
        $shopping_cart = array();
        $_SESSION['cart'] = $shopping_cart;
    }

    print_r($_SESSION['cart']);
?>

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