[php] PHP Unset Session Variable

I'm a noob programmer so I apologies in advance for any obvious mistakes. I've spent the past week creating a product database kinda thing. I've got too the point where I can add products using a form, view all products added etc. I've being using sessions which are created via the form input data. I'm struggling to include get a delete product page working, I've tried using unset to clear the variable but can't get it too work.

ADD Product page which sets the session variable:

$_SESSION['Products'][] = $_POST; //is how i set the session on the add products page. 

unset $_SESSION['Products'][]; //is how i have tried to clear the session although it does not work.

Any point in the right direction will be appreciated!

This question is related to php session

The answer is


If you completely want to clear the session you can use this:

session_unset();
session_destroy();

Actually both are not neccessary but it does not hurt.

If you want to clear only a specific part I think you need this:

unset($_SESSION['Products']);
//or
$_SESSION['Products'] = "";

depending on what you need.


unset is a function, not an operator. Use it like unset($_SESSION['key']); to unset that session key. You can, however, use session_destroy(); as well. (Make sure to start the session with session_start(); as well)


I am including this answer in case someone comes to this page for the same reason I did. I just wasted an embarrassing amount of time trying to track the problem down. I was calling:

unset($_SESSION['myVar']);

from a logout script. Then navigating to a page that required login, and the server still thought I was logged in. The problem was that the logout script was not calling:

session_start();

Unsetting a session var DOES NOT WORK unless you start the session first.


Unset is a function. Therefore you have to submit which variable has to be destroyed.

unset($var);

In your case

unset ($_SESSION["products"]);

If you need to reset whole session variable just call

session_destroy ();

Destroying a PHP Session

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable

<?php    unset($_SESSION['counter']); ?>

Here is the call which will destroy all the session variables

<?php    session_destroy(); ?>

// set
$_SESSION['test'] = 1;

// destroy
unset($_SESSION['test']);