Destroy all sessions but one - php

I have the same problem as this guy: Destroy session, but keep one variable set (solved)
I'm trying to destroy / unset all sessions except one session named 'id' when a user logout.
I don't want to unset each session manually because I have many sessions.
This is my logout.php
<?php
session_start();
foreach($_SESSION as $key=>$value) {
if($key !== "id") {
unset($_SESSION[$key]);
}
}
header("Location: login.php");
exit;
?>
This code currently unsets all sessions and does not keep the session named ID.
What am I missing?

You can reassign $_SESSION['id'] instead of deleting all of the others.
A little trick :)
<?php
session_start();
$tmp = $_SESSION['id'];
session_unset();
$_SESSION['id'] = $tmp;
header("Location: login.php");
exit;
?>

You can also do something like this:
$keep_alive = $_SESSION['id'];
Destroy all sessions:
session_start();
session_destroy();
Set session again:
session_start();
$_SESSION['id'] = $keep_alive;

Related

How to destroy current session but not other session

I have a simple log in system where there are 2 type of user (role: 0,1). If user is role 0 then user is redirected to search.php, else role is 1,redirected to overview.php.
if ($role == 0){
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['email'];
$_SESSION['id'] = $id;
header('Location: search.php');
} elseif ($role == 1) {
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['user'] = $name;
$_SESSION['name'] = $_POST['email'];
$_SESSION['id'] = $id;
header('Location: overview.php');
}
I am able to logout and destroy session, but if both user are logged in and one user logout it will end session for both user.
Here is my logout.php:
<?php
// Initialize the session
session_start();
// Destroy the session.
session_destroy();
header('Location: login.php');
exit;
?>
Then I found this solution source. I was not sure how to get to_destroy_id ($des) so I set it to current session id.
Here is my updated logout.php:
<?php
$des = session_id();
// 1. commit session if it's started.
if (session_id()) {
session_commit();
}
// 2. store current session id
session_start();
$current_session_id = session_id();
session_commit();
// 3. hijack then destroy session specified.
session_id($des);
session_start();
session_destroy();
session_commit();
// 4. restore current session id. If don't restore it, your current session will refer to the session you just destroyed!
session_id($current_session_id);
session_start();
session_commit();
// Redirect to the login page:
header('Location: restTablet.php');
?>
This worked for first time then it stopped working again. Everyone logout if one user logout.
I would just like to destroy user session if they clicked logout, and other users stays logged in. Any idea how can I implement this?
UPDATE: making the following change to logout.php I was able to keep other logged in if one user logout, but once the user logout and tries to go back user is able to access it again without loggin. Here is the logout.php:
<?php
$des = session_id();
// 1. commit session if it's started.
if (session_id()) {
session_commit();
}
// 2. store current session id
session_start();
$current_session_id = session_id();
session_commit();
// 3. hijack then destroy session specified.
session_id($des);
session_start();
session_destroy();
session_commit();
// Redirect to the login page:
header('Location: gabLogin.php');
?>
You can nest your $_SESSION data in a parent level.
For example you have two roles, role 1 and role 2.
Set $_SESSION like the following:
if ($role == 0){
session_regenerate_id();
$_SESSION['role_0']['loggedin'] = TRUE;
$_SESSION['role_0']['name'] = $_POST['email'];
$_SESSION['role_0']['id'] = $id;
header('Location: search.php');
} elseif ($role == 1) {
session_regenerate_id();
$_SESSION['role_1']['loggedin'] = TRUE;
$_SESSION['role_1']['user'] = $name;
$_SESSION['role_1']['name'] = $_POST['email'];
$_SESSION['role_1']['id'] = $id;
header('Location: overview.php');
}
Then when your user logs out of say role_0, unset only the parent session value for that role.
//use logic in logout form to POST proper logout for that role.
if(isset($_POST['logout_0'])){ //--> role_0 is logging out
unset($_SESSION['role_0']); //--> all child data for role_0 should be unset now.
//--> check if user is logged in as alternate role
if($_SESSION['role_1']['loggedin'] === TRUE){
header('Location: overview.php');
}else{
//--> redirect to the page you wish them to go to when logged out
}
}

session_destroy() is not logging me out

Whenever I run the logout.php script then go back to a page that is protected without login it will have me still logged in
logout.php
<?php
session_start();
session_unset();
session_destroy();
header("Location: ../index.php");
exit();
?>
login.php
$userlogin = user_login($email, $password.$salt);
if ($userlogin==false){
$errors[]='Wrong email/password combination.';
} else {
//set the user session
$_SESSION['UserId']=$userlogin;
$_SESSION['LoginIP']=$_SERVER['REMOTE_ADDR'];
$db->query("UPDATE users SET ipadd='".$_SERVER['REMOTE_ADDR']."' WHERE user_id=".$_SESSION['UserId']."");
echo '<meta http-equiv="refresh" content="0; URL=index.php">';
Check logged in snippet
/* Check if user is logged in or not */
function loggedin(){
return (isset($_SESSION['UserId'])) ? true : false;
}
if (loggedin()==true){
$session_user_id = $_SESSION['UserId'];
$user_data = user_data($session_user_id,'full_name','username');
$rezult =$db->query("SELECT ipadd FROM users WHERE user_id=".$_SESSION['UserId']."");
while($rez = $rezult->fetch_assoc()){
if ($rez['ipadd']==$_SERVER['REMOTE_ADDR']) {
} else {
echo '<meta http-equiv="refresh" content="0; URL=logout2.php">';
}
}
}
Been look at posts with the same question but whatever I try still getting the same issue. Any advice would be extremely appreciated!
this is from php.net http://php.net/manual/en/function.session-destroy.php
Note: You do not have to call session_destroy() from usual code. Cleanup $_SESSION array rather than destroying session data.
so you just need $_SESSION = null, and logout should happen.
I think in your index.php file should have these line:
if(!isset($_SESSION["session_name"])){
header("Location: somewhere_mainpage.php");
}
It is better to make all pages have these line. These line will send header to another page if no session has started.
I believe that session_start(); function call should be on your login page when the user login data is correct, and in your logout PHP code, you should set
session_destroy(); or unset($_SESSION['UserId'];
Logout.php:
<?php
session_destroy();
/* * OR * */
//unset($_SESSION['UserId'];
header("Location: ../index.php");
exit();
?>
<?php
session_unset();
session_destroy();
header("Location: ../index.php");
?>
should work, otherwise you could unset the values
<?php
unset($_SESSION['UserId']); // Unsets the UserId Variable reuse for each variable
session_destroy();
header("Location: ../index.php");
?>
have you tried just session_destroy() ?
also I'm not sure wether you need session_start() when you are closing the session, from memory you only need it to start the session
I always like to destroy the server session, and client cookie, try to manually cover all options in case of any errors.
You can destroy the cookie in PHP with:
setcookie(session_name(), '', time() - 3600, $cookie_path, $cookie_domain, $cookie_secure, $cookie_httponly );
<?php
$cookie_path = "...";
$cookie_domain = "...";
$cookie_secure = "...";
$cookie_httponly = "...";
session_start();
session_unset();
session_destroy();
setcookie(session_name(), '', time() - 3600, $cookie_path, $cookie_domain,$cookie_secure, $cookie_httponly );
header("Location: ../index.php");
exit();
time() - 3600 makes the cookie expiry before the current time, which makes it invalid.
Another option to investigate is session_regenerate_id() on your logout pages. Some reference pages are below:
php.net - session-regenerate-id
https://stackoverflow.com/a/22965580/1246494

Why my code doesn't delete the $_SESSION variable?

I have a file where the $_SESSION['username'] variable is first created:
<?php
$kullaniciadi = $_POST['kullaniciadi'];
$sifre = $_POST['sifre'];
if ((!$kullaniciadi =="") and (!$sifre =="")) {
include("db.php");
$sql = $sqlt->query("select * from uye where kullaniciadi='$kullaniciadi' and sifre='".md5($sifre)."'");
$kayitsayisi = mysqli_num_rows($sql);
if ($kayitsayisi == "0") {
header ("Location: login.php?hata=yes");
}
else {
$kontrol_ok = $sql -> fetch_assoc();
$k=$kontrol_ok["kullaniciadi"];
session_start();
$_SESSION['username']= $k;
header ("Location: homepage.php");
}
}
else {
header ("Location: login.php?hata=yes");
}
?>
It is called login_do.php (I send MySQL data from login.php form to here, and do the username and password check in this file).
Than in every other PHP file I have, I begin with:
<?php
session_start();
if (isset($_SESSION["username"])) {
echo 'loginok';
} else {
header ("Location: login.php");
}
?>
Than I have a logout.php, where the user is redirected to if he presses a button. logout.php file contains this:
<?php
session_start();
if(isset($_SESSION['username'])) {
unset($_SESSION['username']);
}
session_destroy();
header("Location: login.php")
?>
But it simply doesn't work. I mean if I go into my browsers cookies and delete the SESSION cookie by myself, than yes, the whole system works and I can't access any other php files than login.php unless I log in. But I need this to work with logout.php instead of me deleting the session from the browser by myself manually.
session_unset();
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.
--http://php.net/manual/en/function.session-destroy.php

how to change session id after logout in php?

<?php
$b = session_id();
if(empty($b)) session_start();
$ses= session_id();
echo $ses;
?>
This code is for generating the session id
But when to destroy the session the session id shown is same as the old one.When I delete the cookie then it has changed..how to change the session id?
Changing the session_id() can be done by session_regenerate_id()
<?php
session_start();
$old_sessionid = session_id();
session_regenerate_id();
$new_sessionid = session_id();
echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";
print_r($_SESSION);
?>
To delete the session use session_destroy();
session_destroy();
$_SESSION = array(); // Clears the $_SESSION variable
http://php.net/manual/en/function.session-destroy.php
May I suggest
// deletes old session
session_regenerate_id(true);
Link to PHP docs

Alternative to PHP deprecated function session_is_registered() for logout.php file

I'm trying to create a simple member login site, and I was following along with a tutorial online. However, a deprecated function is used. Here is the code.
<?php
session_start();
session_destroy();
if(isset($_COOKIE['id']))
{
//remove cookie
setcookie("$id_cookie", '', time() - 50000);
setcookie("$pass_cookie", '', time() - 50000);
}
if(!session_is_registered('username'))
{
header("Location: index.php");
}
else
{
exit('Sorry we could not log you out');
}
?>
I also tried !isset($_SESSION['username']), but every time I try to log out, I just receive the 'Sorry we could not log you out' text.
Here is the part of my login.php file code where I set the sessions:
//member does exist, start sessions
$_SESSION['password'] = $password;
while($row = mysql_fetch_array($query))
{
$username = $row['username'];
$id = $row['id'];
}
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
Any help would be great!
Don't use
session_is_registered
use
if (isset($_SESSION['SESSION_VARIABLE_NAME']))
You may add "session_unset();" before "session_destroy();"
session_destroy() delete the session file and release the session id, but keep the $_SESSION variable in memory.
use this with isset
if(!isset($_SESSION['username']))
Try this
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
if(!isset($_SESSION['username']))
{
header("Location: index.php");
}
Check where the the SESSSION is stored or not.
Try this code in your log out script
<?php
session_start();
if(isset($_SESSION['id']))
{
unset($_SESSION['username']);
unset($_SESSION['id']);
}
if(!isset($_SESSION['username']))
{
header("Location: index.php");
}
else
{
exit('Sorry we could not log you out');
}
?>

Categories