Change session ID and keep data? - php

When a user logs in on our website, I want to change the session ID but keep whatever data is in the session. I want to do this for two reasons:
To prevent a user account to be used at multiple places simultaneously (because if two people are using the same account, the actions of one will undermine the actions of the other).
To let the user continue what he/she was doing on another computer (e.g moving from home computer to work).
These might seem contradictory, but really aren't if you think it through.
The problem is as follows; to get to the data that is currently in the session, I have to call session_start(). This means I cannot call session_id() afterwards to set a new session ID. Any ideas how to transfer the session data and change the session ID.
Update: I need to be able to choose the session ID myself. session_regenerate_id() therefore won't work.

You might be able to use 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);
?>
or even a cruder approach might work:
// save the session
session_start();
$session = array();
foreach ($_SESSION as $k => $v) {
$session[$k] = $v;
}
session_commit();
// create new session and copy variables
session_id("new session id");
session_start();
foreach ($session as $k => $v) {
$_SESSION[$k] = $v;
}

Use this. Put it to a function:
function update_session($newsessid = '') {
// Backup the current session
$session_backup = $_SESSION;
// Set current session to expire in 1 minute
$_SESSION['OBSOLETE'] = true;
$_SESSION['EXPIRES'] = time() + 60;
// Close the current session
session_write_close();
// Set a new session id and start the session
$newSession = session_id($newsessid);
session_start();
// Restore the previous session backup
$_SESSION = $session_backup;
// Clean up
unset($session_backup);
unset($_SESSION['OBSOLETE']);
unset($_SESSION['EXPIRES']);
}
You would then call it when required:
update_session($customid);

Or, you may just be able to use something like this:
$path=session_save_path();
$whatever_session_id;
pass these variables to the next page:
session_id()=$whatever_session_id;
session_save_path()=$path;
You'd be setting the path of the new session id to the old session data....
I don't know if this is really what you'd want, be here it is.

Related

PHP Cookies Show Login Account List Gmail Like

I would like to implement multiple user login show like gmail login. See below image:
Current I'm using COOKIE to get the USERID. But it only give me the last USERID. not all.
Here is PHP to set COOKIE:
setcookie("cookielogin[userLoginRemembered]", $dataLoginQuery['USERID'] , $time + (60*60*24*7));
What I want is, to show all user ever logged in and display it using COOKIE.
Is it possible?
Because you only store last logged user id into cookie, and it overrides old value
Cookie only stores raw text, so if you want to store a list (array), you have to serialize it (by your own way or using serialize() function). This
sample code below uses PHP's serialize():
$lastLoggedUserId = '123';
if (!isset($_COOKIE['cookie_key_for_logged_users'])) {
$cookieLoggedUserIds = [$lastLoggedUserId];
} else {
// unserialize
$cookieLoggedUserIds = (array) unserialize($_COOKIE['cookie_key_for_logged_users']);
$cookieLoggedUserIds[] = $lastLoggedUserId;
}
// just to make sure no duplicated user id to be stored
$cookieLoggedUserIds = array_unique($cookieLoggedUserIds);
setcookie('cookie_key_for_logged_users', serialize($cookieLoggedUserIds));
print_r(unserialize($_COOKIE['cookie_key_for_logged_users']));
I've not tested this code, but it's easy to test and tweak.
You need to append the information in the cookie.
There is no append for cookies so what we need to do is read it's current value, add current string and write a new cookie.
$currentvalue = $_COOKIE["cookielogin[userLoginRemembered]"];
If(strpos($currentvalue, $dataLoginQuery['USERID']) !== false){
Echo "username exist in cookie already";
}else{
setcookie("cookielogin[userLoginRemembered]", $currentvalue .",". $dataLoginQuery['USERID'] , $time + (60*60*24*7));
//Here I set the value of cookie as current value and dataloginquery.
}
Output:
Var_dump(explode(",", $_COOKIE["cookielogin[userLoginRemembered]"]));
// Dumps the array of usernames that is comma separated.

How to pass variable to another page without include

Hey guys I'm trying to pass a php variable to another page. I tried it with sessions but no result.
newspaper.php
$newspaper= $newspaper['newspath'];
print_r($newspaper);
this outputs:
path/to/the/newspaper.
Now I want to use the variable in the second page.
newspaperviewer.php
echo $newspaper;
$SESSION = $newspaper;
I tried the first one but no result. The second one seems to be faulty.
Hope you guys can help me out.
Session is what you are looking for. A session variable can store a value and use this value on all pages of your project.
First thing to do is to start session on each file on your project. You can do this like this example
<?php
session_start(); //declare you are starting a session
$_SESSION['newspaper'] = "New York Times"; //Assign a value to the newspaper session
?>
On the other file you can use the value of the session by trying something like this
<?php
session_start(); //always start session don't forget!!
echo $_SESSION['newspaper'];
// This will echo New York Times
?>
Store the variable after starting session on page A, like so:
// FIRST PAGE (foo.php)
session_start();
$_SESSION['name'] = 'Jack';
Now, on the second page (or any page that you want to have access to $_SESSION, simply do the same but pull the variable.
// SECOND PAGE (bar.php)
session_start();
$name = $_SESSION['name'];
$_SESSION['name'] = null; // Or use session_unset() to delete all SESSION vars.
And that's how you pass variables using $_SESSION.
Please use this code to set session
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
You can write like this
newspaper.php
session_start();
$newspaper= $newspaper['newspath'];
$_SESSION['newspaper'] = $newspaper;
Now you can use this session variable in
newspaperviewer.php
session_start();
$newspaper = $_SESSION['newspaper'];
echo $newspaper;
session_unset(); // remove all session variables
First
newspaper.php
$newspaper= $newspaper['newspath'];
//print_r($newspaper);
session_start(); //it starts your session here
$_SESSION['newspaper']=$newspaper; //it sets a session variable named as newspaper
Second
$newspaper= isset($_SESSION['newspaper'])?$_SESSION['newspaper']:''; //checks and sets value
echo $newspaper; //outputs value
For more see session_start
http://php.net/manual/en/session.examples.basic.php
First you will need to start the session by using session_start() at the top of your page. Second, a session variable is written like this: $_SESSION['foo'].
I suggest you read these pages to get a better understanding of what's going on.
http://php.net/manual/en/reserved.variables.session.php
http://www.w3schools.com/php/php_sessions.asp

session_destroy not unsetting the session_id

I am working on an online ticket booking systems where after making successful booking(after payment) I want to clear the session id. But the thing is I am not able to clear it although I have used session_destroy() to destroy the session.
NB: I have echoed the session_id to check if its reset or not.
URL: http://7sisters.in/7sislabs/
function book_final_tickets()
{
//var_dump($_SESSION);
$session_id = session_id();
$sql = "
UPDATE
tbl_seat_book
SET
final_book = 'Y'
WHERE
session_id = '$session_id'
";
//session_unset();
if($r = $this->db->executeQuery($sql)){
if(session_destroy()){
unset($session_id);
echo 'Booking successfull';
}
}
}
session_destroy() alone won't remove the client-side cookie, so the next time the user visits, they'll still have the same session id set (but their server-side session info will have been destroyed).
From the docs (emphasis mine):
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. ... 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.
You can use session_regenerate_id(true) to generate a new session ID and delete the old one. Note that this will keep all of the information in $_SESSION as part of the new session ID, so you still need to use session_destroy if you want to clear the session info and start fresh.
e.g.
<?php
session_start();
$_SESSION['blah'] = true;
var_dump(session_id()); // q4ufhl29bg63jbhr8nsjp665b1
var_dump($_SESSION); // blah = true
session_unset();
session_destroy();
setcookie("PHPSESSID", "", 1); // See note below
session_start();
session_regenerate_id(true);
var_dump(session_id()); // gigtleqddo84l8cm15qe4il3q3
var_dump($_SESSION); // (empty)
?>
and the headers will show the session ID changing on the client-side:
Request Header
Cookie:PHPSESSID=q4ufhl29bg63jbhr8nsjp665b1
Response Header
Set-Cookie:PHPSESSID=deleted; expires=Mon, 27-Dec-2010 16:47:57 GMT
PHPSESSID=gigtleqddo84l8cm15qe4il3q3; path=/
(You can get away without the setcookie() call here, since you're creating a new session anyway, so the cookie will be overwritten by the new ID, but it's good practice to explicitly destroy the old cookie).
After destroying the session with session_destroy(), this worked for me:
setcookie('PHPSESSID',"",time()-3600,'/');
The key for me was setting the path to '/'. That was the only way to really destroy the cookie.
Call session_id before session_start, and set session_id manually .
Example 1: same session_id will be used
<?php
session_start();
echo session_id(); //4ef975b277b52
session_destroy();
session_start();
echo session_id(); //4ef975b277b52
?>
Example 2: set session_id manually (called before session_start())
<?php
session_id(uniqid());
session_start();
echo session_id(); //4ef975d3d52f5 (A)
session_destroy();
session_id(uniqid());
session_start();
echo session_id(); //4ef975d3b3399 (B)
?>
(A) != (B), so you can set session_id manually, see http://php.net/manual/en/function.session-id.php for more information.
Another solution, dont use session_id() , just create new session array:
<?php
$_SESSION['booked'] = false;
if($r = $this->db->executeQuery($sql))
{
$_SESSION['booked'] = true;
echo 'Booking successfull';
}
?>
Try this:
unset($session_id);
session_destroy();
Instead of
session_destroy();
I'd rather do only a
session_regenerate_id(true);
and you will get a new session_id

Erasing a session and getting a new session_id() in PHP

Not sure what to do... I have this on my logout page:
<?php
setcookie ("session_key", "", time() - 3600);
session_start();
$_SESSION = array();
session_unset();
session_destroy();
header('Location:login.php');
?>
but still, when a new user "signs up" after logging out they get the same session id therefore causing some issues with logging in as multiple people then have the same session id.
Ideas?
What is wrong with session_regenerate_id(true); $_SESSION = array(); ?
It seems to do exactly what you want.

Magento - Checking if an Admin and a Customer are logged in

I have a web server with Magento 1.4.0.1 installed. I have another web site that shares credential with it. I've managed to check if the customer is logged in or not (after having changed the cookies location in Magento), but things got complicated when I also tried to figure out if an admin was logged in. I can only get the proper answer for the first session I asked for (either the customer OR the admin, the second one is NEVER logged in).
How can I have both answers?
Here is the code I'm using to test that out:
require_once '../app/Mage.php';
umask(0) ;
Mage::app();
// Checking for customer session
Mage::getSingleton('core/session', array('name'=>'frontend') );
$session=Mage::getSingleton('customer/session', array('name'=>'frontend') );
if ($session->isLoggedIn()) {
echo "Customer is logged in";
} else {
echo "Customer is not logged in";
}
// Checking for admin session
Mage::getSingleton('core/session', array('name'=>'adminhtml') );
$adminsession = Mage::getSingleton('admin/session', array('name'=>'adminhtml'));
if($adminsession->isLoggedIn()) {
echo "Admin Logged in";
} else {
echo "Admin NOT logged in";
}
So with the code like this, the admin is never logged in. If you put the part about the admin first, then the customer is never logged in. It seems like I'm missing a line between the two requests.
This may be the same problem than this unanswered question: Magento how to check if admin is logged in within a module controller
This seems like a popular problem, but I could not find the proper solution...
Thanks for your help!
I've found that "bug-feature" from another angle of view (trying to login customer from adminside), but still found the cause.
The problem is with session_name() function. If you go to Mage_Core_Model_Session_Abstract_Varien you'll see there that the session object is using standart PHP session functions and PHP can't handle two sessions at the same time.
You session id for adminside is stored in cookie adminhtml, while for clientside your session id is in frontend cookie. Then in adminside you have session ID initialized by adminhtml cookie. When in adminside, your customer/session object is stored inside something like $_SESSION['customer'] (haven't checked exact key) inside PHP session for ID stored in adminhtml cookie. This means that customer/session object is refering to different sessions when inside admin and client parts of magento.
What you need to do is switch the session data. You can do this with the following code:
$switchSessionName = 'adminhtml';
$currentSessionId = Mage::getSingleton('core/session')->getSessionId();
$currentSessionName = Mage::getSingleton('core/session')->getSessionName();
if ($currentSessionId && $currentSessionName && isset($_COOKIE[$currentSessionName])) {
$switchSessionId = $_COOKIE[$switchSessionName];
$this->_switchSession($switchSessionName, $switchSessionId);
$whateverData = Mage::getModel('mymodule/session')->getWhateverData();
$this->_switchSession($currentSessionName, $currentSessionId);
}
protected function _switchSession($namespace, $id = null) {
session_write_close();
$GLOBALS['_SESSION'] = null;
$session = Mage::getSingleton('core/session');
if ($id) {
$session->setSessionId($id);
}
$session->start($namespace);
}
Here is what I use..
Mage::getSingleton('core/session', array('name'=>'adminhtml'));
$session = Mage::getSingleton('admin/session');;
if (!$session->getUser())
{
die("You aren't an admin!");
}
It is quite simple but not a recommended solution. I myself spend number of hours to do this.
For, windows based server try below solution:
$sessionFilePath = Mage::getBaseDir('session').DS.'sess_'.$_COOKIE['adminhtml'];
$sessionFile = file_get_contents($sessionFilePath);
$exp_cookie = explode(';',$sessionFile);
if(count($exp_cookie) > 100)
{
return "login";
}
return "expire";
For, Linux based server try below solution:
$sessionFilePath = Mage::getBaseDir('session').DS.'sess_'.$_COOKIE['adminhtml'];
$sessionFile = file_get_contents($sessionFilePath);
$exp_cookie = explode('--',$sessionFile)
if(count($exp_cookie) > 10)
{
return "login";
}
return "expire";
Thanks,
Kashif
Here is a simple script to check admin is logged or not and if logged get admin details of Magento.You can call to the session and the call to user function to get all details.
$userDetails = Mage::getSingleton('admin/session'); // Get data from the session
$userID = $userDetails->getUser()->getUserId(); // Get user ID
$userID = $userDetails->getUser()->getEmail(); // Get user Email
Please refer to http://webexplorar.com/magento-admin-details/ for more details.

Categories