Destroying a session if it already exists? - php

What I am trying to do:
When a user hits the index.php page (the start of a couple pages of forms), I need any existing session to be destroyed and a new one to start. This is so that old session variables are not reused in the new process.
What I have done:
I believe this should check if a session already exists, if it does, destroy it and start a new one. (Need to use session_id() for the check)
if(session_id() == '') {
session_start();
}else{
session_destroy();
session_start();
}
The issue:
The previous session variables are still set and causing issues with the process.
Am I missing something in the way to reset all session varibles?

In documentation you can read:
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with
the session, or unset the session cookie. session_destroy();
So you have to do following things:
$_SESSION = array(); //empty session variable
$cookieParams = session_get_cookie_params();
setcookie(
session_name(),
'',
0,
$cookieParams['path'],
$cookieParams['domain'],
$cookieParams['secure'],
$cookieParams['httponly']
);
session_destroy(); //and now you can call your function

Related

User authorization php/mysql with session [duplicate]

I have heard mixed responses on this topic, so what is a sure fire way to destroy a PHP session?
session_start();
if(isset($_SESSION['foo'])) {
unset($_SESSION['foo'];
...
}
session_destroy();
In the most simple of cases, would this sufficient to truly terminate the session between the user and the server?
To destroy a session you should take the following steps:
delete the session data
invalidate the session ID
To do this, I’d use this:
session_start();
// resets the session data for the rest of the runtime
$_SESSION = array();
// sends as Set-Cookie to invalidate the session cookie
if (isset($_COOKIE[session_name()])) {
$params = session_get_cookie_params();
setcookie(session_name(), '', 1, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
}
session_destroy();
And to be sure that the session ID is invalid, you should only allow session IDs that were being initiated by your script. So set a flag and check if it is set:
session_start();
if (!isset($_SESSION['CREATED'])) {
// invalidate old session data and ID
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
Additionally, you can use this timestamp to swap the session ID periodically to reduce its lifetime:
if (time() - $_SESSION['CREATED'] > ini_get('session.gc_maxlifetime')) {
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
The PHP Manual addresses this question.
You need to kill the session and also remove the session cookie (if you are using cookies).
See this page (especially the first example):
http://us2.php.net/manual/en/function.session-destroy.php
In the one site I've made where I did use PHP sessions, I never actually destroy the session.
The problem is that you pretty much have to call session_start() to check for your $_SESSION variables, at which point, lo and behold, you've created another session anyway.
Hence on my site I just made sure that every page called session_start(), and then just unset() those parts of the session state that matter when the user logs off.
$_SESSION = [];
#unset($_COOKIE[session_name()]);
session_destroy();

PHP Session not clearing?

I am using PHP sessions for a tool I have created. It allows for you to resume a previous session you may have started that is stored in the database. All that functionality is working as intended.
However, I provide a link that says "Create New Session" and point it to a PHP page that contains this code:
<?php
session_start();
session_destroy();
$_SESSION = array();
unset($_SESSION);
header('Location: wizard.php');
?>
Now, when it redirects back to wizard.php, I have it printing out all session details and it still contains information from the previous session.
Is there something I am missing here?
Wizard.php starts with session_create(); so I would assume as soon as it redirected it would create a new session ID and all which isnt happening.
Thanks for any info
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// Finally, destroy the session.
session_destroy();
header('Location: wizard.php');
?>
Taken from: session_destroy Example 1

Session taking its own sweet time to be Destroyed

I have created a user page with a menu that contains a logout button. Upon clicking the button, the user is directed to a logout page with the following code:
session_start();
session_destroy();
include("/var/www/include/header.inc");
echo "<h>Logout Success</h>";
include("/var/www/include/menu.inc");
include("/var/www/include/footer.inc");
The code in the menu.inc file is written such that:
if(#$_SESSION['login'] == "yes")
{
// show expanded menu
}
else
{
// show normal menu
}
What I am seeing now after logging out is the expanded menu. It seems that the menu is being included faster than the session can be destroyed, thus creating an impression that the user is still logged in. Is there a way to avoid such a situation?
session_destroy doesn't unset the $_SESSION array, so the rest of the page after session_destroy will still see it. You could simply try this
session_destroy();
unset($_SESSION);
session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.
Source.
To completely clear all session data you have to use something similar to
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
This is explained in PHP manual:
session_destroy() destroys all of the data associated with the current
session. It does not unset any of the global variables associated with
the session, or unset the session cookie. To use the session variables
again, session_start() has to be called.
In order to kill the session altogether, like to log the user out, the
session id must also be unset. If a cookie is used to propagate the
session id (default behavior), then the session cookie must be
deleted. setcookie() may be used for that.

SESSION variables not passed from page after destroying the rest

I am at a total loss for words.
I allow an admin to reset their registration if reaching an error during the process. In theory, the following code should function like this:
page is reached, $adminvalidated is set based on session data. The $_SESSION array is cleared; the cookie is cleared on the consumer end; the session id is regnerated and the session is destroyed. Then the session is restarted and the previously mentioned variable is put back into Session.
the "echo" statements included below work but when I redirect to another page (commented out below), the session variables DO NOT carry over.
Yes I have started the session on the follow up page as well.
<?php
session_start();
ob_start();
if( $_SERVER['SERVER_PORT'] == 80) {
header('Location:https://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]);
die();
}
$adminvalidated = $_SESSION['ADMINVALIDATED'];
$_SESSION = array();
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_regenerate_id(true);
session_destroy();
session_start();
$_SESSION['ADMINVALIDATED'] = $adminvalidated;
echo $_SESSION['ADMINVALIDATED'];
/*
header("Location: ../a.php");
exit;*/
?>
In general it suffices to call session_regenerate_id(true) to change the session ID of the current session and invalidate the association with the previous session ID.
If you additionally want to clear any session data except $_SESSION['ADMINVALIDATED'], just do this:
session_regenerate_id(true);
$_SESSION = array(
'ADMINVALIDATED' => $_SESSION['ADMINVALIDATED']
);
From the manual page of session_start:
As of PHP 4.3.3, calling session_start() after the session was previously started will result in an error of level E_NOTICE. Also, the second session start will simply be ignored.
Just clear your session with session_unset, regenerate the session id and then reset your admin var. No need to destroy then restart the session.
I'm really not sure why you're going through all of these steps. session_regenerate_id() is enough on it's own to regenerate the session token and the associated cookie. The function creates a new session token and creates a new session cookie for you while preserving the values you have in the current session. Since setting a new cookie with the same name overwrites an old one isn't simply calling session_regenerate_id() enough?
Feel free to clarify things if I've missed something.

Truly destroying a PHP Session?

I have heard mixed responses on this topic, so what is a sure fire way to destroy a PHP session?
session_start();
if(isset($_SESSION['foo'])) {
unset($_SESSION['foo'];
...
}
session_destroy();
In the most simple of cases, would this sufficient to truly terminate the session between the user and the server?
To destroy a session you should take the following steps:
delete the session data
invalidate the session ID
To do this, I’d use this:
session_start();
// resets the session data for the rest of the runtime
$_SESSION = array();
// sends as Set-Cookie to invalidate the session cookie
if (isset($_COOKIE[session_name()])) {
$params = session_get_cookie_params();
setcookie(session_name(), '', 1, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
}
session_destroy();
And to be sure that the session ID is invalid, you should only allow session IDs that were being initiated by your script. So set a flag and check if it is set:
session_start();
if (!isset($_SESSION['CREATED'])) {
// invalidate old session data and ID
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
Additionally, you can use this timestamp to swap the session ID periodically to reduce its lifetime:
if (time() - $_SESSION['CREATED'] > ini_get('session.gc_maxlifetime')) {
session_regenerate_id(true);
$_SESSION['CREATED'] = time();
}
The PHP Manual addresses this question.
You need to kill the session and also remove the session cookie (if you are using cookies).
See this page (especially the first example):
http://us2.php.net/manual/en/function.session-destroy.php
In the one site I've made where I did use PHP sessions, I never actually destroy the session.
The problem is that you pretty much have to call session_start() to check for your $_SESSION variables, at which point, lo and behold, you've created another session anyway.
Hence on my site I just made sure that every page called session_start(), and then just unset() those parts of the session state that matter when the user logs off.
$_SESSION = [];
#unset($_COOKIE[session_name()]);
session_destroy();

Categories