Can You Switch PHP Sessions In a Session?

user73579 picture user73579 · Mar 4, 2009 · Viewed 10.8k times · Source

I have two apps that I'm trying to unify. One was written by me and another is a CMS I am using. My authentication happens in the one I coded and I'd like my CMS to know that information. The problem is that the CMS uses one session name, and my app uses another. I don't want to make them use the same one due to possible namespace conflicts but I'd still like to get this information.

Is it possible to switch session names in the middle of a request? For example, doing something like this in the CMS:

//session_start already called by cms by here

$oldSession = session_name();
session_name("SESSION_NAME_OF_MY_APP");
session_start();

//get values needed
session_name($oldSession);
session_start();

Would something like this work? I can't find anything in the docs or on the web if something like this would work after session_start() has been called. Tips?

Baring this solution, I've been considering just developing a Web Service to get the information, but obviously just getting it from the session would be preferable as that information is already available.

Thanks!

Answer

a_w picture a_w · Oct 25, 2010

Here is a working example how to switch between sessions:

session_id('my1session');
session_start();
echo ini_get('session.name').'<br>';
echo '------------------------<br>';
$_SESSION['value'] = 'Hello world!';
echo session_id().'<br>';
echo $_SESSION['value'].'<br>';
session_write_close();
session_id('my2session');
session_start();
$_SESSION['value'] = 'Buy world!';
echo '------------------------<br>';
echo session_id().'<br>';
echo $_SESSION['value'].'<br>';
session_write_close();
session_id('my1session');
session_start();
echo '------------------------<br>';
echo $_SESSION['value'];

Log will look like:


PHPSESSID
------------------------
my1session
Hello world!
------------------------
my2session
Buy world!
------------------------
Hello world!

So, as you can see, session variables saved and restored while changing session.