tags:

views:

65

answers:

4

i am making a 10 question survey with one question at a point. i made a session for passing values between questions. the thing i discovered is that the session values do not get destroyed even on a page refresh. is there a workaround or am i doing something wrong.

just to make things clear, here is the code:

session_start(); 
//  $_SESSION['score'] = $score;
    $_SESSION['qnum'] = isset($_SESSION['qnum']) ? $_SESSION['qnum']+1 : 1;

    if ($_SESSION['qnum'] < 10){
        $_SESSION['total'] = isset($_SESSION['total']) ? $_SESSION['total']+$score : $score;
    }
    else if ($_SESSION['qnum'] == 10){
        $_SESSION['total'] = isset($_SESSION['total']) ? $_SESSION['total']+$score : $score;
        echo "finished";
    }

    echo $_SESSION['qnum'];
    echo '\n';
    echo $_SESSION['total'];
+3  A: 

$_SESSION variables will remain until you terminate the session or unset() the session variable.

To end a session try this code:

$_SESSION = array();
session_unset();
session_destroy();

To delete a session variable use:

unset($_SESSION['variablename']);
John Conde
And $_SESSION variables are build to survive the page refresh be design. Hard to keep the user logged into otherwise.
Mark Tomlin
wrt the code above, how do you suggest to destroy the session? i mean if i destroy the session just after the code above, wont it make passing calls difficult?
amit
If you destroy the whole session it will defeat the purpose of the session which is to track data across pages a.k.a. for a session. You probably just need to delete individual session variables when they are no longer required.
John Conde
+2  A: 

That's the whole point of sessions - they stick around for the browsing session. You're using them like run-of-the-mill variables, which causes me to ask: why not just use normal variables?

ceejayoz
A: 

This is whole beauty and concept of session varible that it will not destroy untill or unless you destroy or unset it. What the problem , your code is completely correct , You are saving question number and total score as a session variable and score as a local .just do one thing at the end of Quiz destroy the session using sesion_destroy()

vinayrks
A: 

Hidden variables may be a better tool to use for your purpose. Session variables by nature are built to last the whole application session.

Prasanna