Session variables keep resetting

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
phpnitemare
Forum Newbie
Posts: 12
Joined: Sat Mar 28, 2009 1:14 pm

Session variables keep resetting

Post by phpnitemare »

Hello,

I have started a session in index.php, which allows the variables to be used in basket.php

I add 1 to the variable in basket.php but when loading the index.php the variable gets reset.

I have tried to say only reset variables when there is no session id, although this seems to fail. How do I initialise variables at the start of a session and ensure they are not reset as the variables are changes as they are used throughout the other pages.

The code below is in index.php

Code: Select all

if(session_id()==0){
$carttest[] = array(30);
 
$_SESSION["carttest"] = $carttest;
$pointer = 0;
$_SESSION["pointer"] = $pointer;
}

This code is in basket.php

Code: Select all

$newpointer = $_SESSION['pointer']; 
$receivecartid = $_SESSION['carttest']; 
$receivecartid[$newpointer] = $_POST['album_id'];
$newpointer = $newpointer +1;
$_SESSION['pointer'] = $newpointer;
Thanks
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Session variables keep resetting

Post by Christopher »

You have to call session_start() to load the values into the $_SESSION superglobal on every page where you want to access it.
(#10850)
phpnitemare
Forum Newbie
Posts: 12
Joined: Sat Mar 28, 2009 1:14 pm

Re: Session variables keep resetting

Post by phpnitemare »

Hi,

Thanks, i saw that i must have commented it out :oops:

I have a problem now of the variables getting reset each time the main index.php is loaded should a user wish to go back to view items after adding one to the basket. I therefore added an initial check to set the default values once based on sessioncode being equal to 0, after which the variable is assigned sessionid().

Therefore now I am unable to reset the values, i have seen a function session_destroy/unset. Would this help in this situation, if I was to add a button, 'clear basket' which ran a function similar would this clear the session or at least reset the core values?

Code: Select all

$_SESSION["sessioncode"] = 0;
$sessioncode = $_SESSION["sessioncode"];
if($_SESSION["sessioncode"]=0){
$pointer = 0;
$_SESSION["pointer"] = $pointer;
}
$sessioncode = session_id();
Post Reply