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 »

Hi,


I have a problem with 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();
User avatar
greyhoundcode
Forum Regular
Posts: 613
Joined: Mon Feb 11, 2008 4:22 am

Re: Session variables keep resetting

Post by greyhoundcode »

In short, replace = with == when making a comparison.

In your code you are evaluating an assignment - you are assigning zero to $_SESSION['sessioncode'], and the outcome is true:

Code: Select all

if ($_SESSION["sessioncode"] = 0)
{
    $pointer = 0;
    $_SESSION["pointer"] = $pointer;
}
What you should do instead is compare zero against $_SESSION['sessioncode']:

Code: Select all

if ($_SESSION['sessioncode'] == 0)
{
    $pointer = 0;
    $_SESSION["pointer"] = $pointer;
}
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Session variables keep resetting

Post by Apollo »

phpnitemare wrote:if($_SESSION["sessioncode"]=0)
you probably meant == right? ;)

(edit) oh, too late I guess, didn't see the above reply before.

By the way, coding tip of the day - the above issue is a typical reason why

Code: Select all

if (0==$x)
is better than

Code: Select all

if ($x==0)
because they do exactly the same, except the first won't allow you to make that single = mistake.
Post Reply