0

Possible Duplicate:
How to unset/destroy all session data except some specific keys?

I am having certain session variables starting with "cars" such as

$_SESSION["cars_registration"];
$_SESSION["cars_make"];
$_SESSION["cars_model"];
$_SESSION["cars_variant"];
.
.
.
$_SESSION["cars_date_created"];

I want to know the code for unsetting / deleting / emptying only those session variables which starts with cars as prefix like above.

So far I have achieved this but dont have any idea about code for unsetting them.

foreach($_SESSION as $key => $value)
{
    if (strpos($key, 'cars_') === 0)
    {
      // Need to delete / unset the session variables  
    }
}

Please help me with it

Community
  • 1
  • 1
Asnexplore
  • 363
  • 1
  • 7
  • 25

5 Answers5

6

Well, I'm glad to see that is still capable of ignoring the glaringly obvious.

There are many ways that you can do this with loops and all sorts of things, however the right way to do this would be to use a sub array cars, which you can easily destroy in one go.

So instead of creating

$_SESSION["cars_registration"];
$_SESSION["cars_make"];

etc, you would create:

$_SESSION["cars"]["registration"];
$_SESSION["cars"]["make"];

So when you come to unset it, you simply need to do:

unset($_SESSION["cars"]);

$_SESSION can hold data in a multi-dimensional structure just like any other array - it does not need to be a flat collection of values.

DaveRandom
  • 87,921
  • 11
  • 154
  • 174
4

you almost got it!!!

 foreach($_SESSION as $key => $value)
    {
        if (strpos($key, 'cars_') === 0)
        {
          unset($_SESSION[$key]); //add this line
        }
    }

here are some few explanations. inside the foreach you set $key to be a variable to hold the key of the $_SESSION array for each iteration and it works the same with the $value

reference:

http://php.net/manual/en/control-structures.foreach.php

Netorica
  • 18,523
  • 17
  • 73
  • 108
3

Just use unset.

foreach($_SESSION as $key => $value)
{
    if (strpos($key, 'cars_') === 0)
    {
      unset($_SESSION[$key]);
    }
}
Michael
  • 930
  • 5
  • 8
0

session_unregister — Unregister a global variable from the current session This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

session_unset — Free all session variables Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

session_destroy — Destroys all data registered to a session

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
0

With PHP, you can use unset to 'destroy' a variable. So, once you're convinced the key meets your criteria you can do:

unset($_SESSION($key));
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129