Search code examples
phpsessionsession-variablesunset

Unset session when leaving page


How can I unset SESSION['variables'] when user is leaving a page, without having to include something on the top of every single page which I have on my site?

Any best practises around you might know of?

Thanks.

EDIT

I have a wizard for setting up a company and a customer.This includes 2 pages: 1 for company and 1 for customer. If the user wants to re-use the data filled in at the company for the customer, he can check the checkbox and when form at page 1 (company) is posted, at page 2 (customer) those fields are automatically set (think about fields like: postal adress, street, phone etc.). The user can access page 1 and page 2 whenever he wants, so I have to unset the session else it will keep auto-filling in the fields.

I can unset the session after the fields are set on page 2, but when he refreshes the browser, the fields become empty again. This is not a big problem ofcourse, but isn't there an easy way to only unset these sessions when the user goes to any other page (without exiting browser and within my website)?

EDIT

My code:

Company page:

$_SESSION['wizard2']= "true"; // used for manipulating page when entering in wizard mode
if (isset($_POST['savedata'])) // if user wants to re-use data from page1
{
$_SESSION['savedata'] = "true";
$_SESSION['custprovincesession']=mysql_real_escape_string($_POST['compprovince']);
header("Location:customer_page.php");
exit();

Customer page:

if (isset($_SESSION['wizard2'])) // used for manipulating page when entering in wizard 
{
    unset ($_SESSION['wizard2']);
}
if (isset($_SESSION['savedata'])) // if user wants to re-use data from page1
{
    $_SESSION['wizard3'] = "true";
}


  <tr>
    <th><label for="custprovince">Province:</label></th>
    <th><input type="text" name="custprovince" style=width:200px id="custprovince" size="8" value="<?php if (isset($_SESSION['wizard3']))   {   echo $_SESSION['custprovincesession'];}?>"/></th>
    <th>&nbsp;</th>
    <th>&nbsp;</th>
  </tr>

at the end of page 2:

if (isset($_SESSION['wizard3']))
{
    unset ($_SESSION['wizard3']);
    unset ($_SESSION['custprovincesession']);
}

Because of this, by refreshing the page the sessions are unset. Is there no other way to unset these sessions when the user leaves the "customer_page.php"?


Solution

  • This might be a silly question, but why would you want to unset certain session variables on every page?

    Surely the point of the session is to persist across page views, and thus you would only want to unset or clear it at specific trigger points (such as a user logging out of the system.

    To answer the question, many frameworks would generally use a single entry point for all scripts, which does any initialisation, farms off the actual page work to a controller, and then return to the single entry point. If you use this methodology then you can put any closing logic at the end of the page.