Destroying a session...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Swede78
Forum Contributor
Posts: 198
Joined: Wed Mar 12, 2003 12:52 pm
Location: IL

Destroying a session...

Post by Swede78 »

I thought this would work, but it doesn't. Hence... I am here, asking for help from helpful people.

I want to destroy a session, but keep 2 session variables. Basically, clean out 20+ session variables, and start over with the same user. Problem is that the user info is stored in sessions. I'd like to avoid unsetting that many variables. I know that's not too much work, but I'd like to understand how to do things better.

Code: Select all

$UserName = $_SESSION['UserName'];
$UserID = $_SESSION['UserID'];

session_unset();
session_destroy();

$_SESSION['UserName'] = $UserName;
$_SESSION['UserID'] = $UserID;
Is what I'm trying to do, possible? Other than just unsetting all the variables I don't want to keep?

Thanks in advance.
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post by liljester »

that way, you terminate one session, and start a completely new session with the vars you want =)

Code: Select all

<?php
$UserName = $_SESSION['UserName']; 
$UserID = $_SESSION['UserID']; 

session_destroy(); 
session_start();

$_SESSION['UserName'] = $UserName; 
$_SESSION['UserID'] = $UserID;
?>
User avatar
delorian
Forum Contributor
Posts: 223
Joined: Sun May 04, 2003 5:20 pm
Location: Olsztyn, Poland

Post by delorian »

It's better to do it this way:

Code: Select all

<?php 
$UserName = $_SESSION['UserName']; 
$UserID = $_SESSION['UserID']; 

$_SESSION = array();
unset($_COOKIE[session_name()]);
session_destroy(); 
session_start(); 

$_SESSION['UserName'] = $UserName; 
$_SESSION['UserID'] = $UserID; 
?>
Session_destroy() doesn't always do what it should do. So for sure I clean the $_SESSION table and remove the session cookie.
Swede78
Forum Contributor
Posts: 198
Joined: Wed Mar 12, 2003 12:52 pm
Location: IL

Post by Swede78 »

Thanks,

I see that I forgot that I need to re-start the sessions.

Isn't session_unset() the same as unset($_COOKIE[session_name()]) ?
User avatar
delorian
Forum Contributor
Posts: 223
Joined: Sun May 04, 2003 5:20 pm
Location: Olsztyn, Poland

Post by delorian »

Swede78 wrote:Isn't session_unset() the same as unset($_COOKIE[session_name()]) ?
No, the unset() functions can "kill" all types of variables, session_unset() free all SESSION variables, and nothing else.
Post Reply