Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Unset Session Variable

Tags:

php

session

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!

like image 491
bbowesbo Avatar asked Jun 02 '16 08:06

bbowesbo


People also ask

How do I remove a specific session variable in PHP?

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.

Which function is used to remove session variable PHP?

If you want to destroy all the session variables, then use the following PHP function. session_destroy();

What is PHP session_start () and session_destroy () function?

session_destroy() function: It destroys the whole session rather destroying the variables. When session_start() is called, PHP sets the session cookie in browser. We need to delete the cookies also to completely destroy the session. Example: This example is used to destroying the session.


2 Answers

You can unset session variable using:

  1. session_unset - Frees all session variables (It is equal to using: $_SESSION = array(); for older deprecated code)
  2. unset($_SESSION['Products']); - Unset only Products index in session variable. (Remember: You have to use like a function, not as you used)
  3. session_destroy — Destroys all data registered to a session

To know the difference between using session_unset and session_destroy, read this SO answer. That helps.

like image 142
Thamilhan Avatar answered Sep 29 '22 08:09

Thamilhan


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 (); 
like image 32
Don D Avatar answered Sep 29 '22 06:09

Don D