PHP 8.6.0 Beta 1 is available for testing

Voting

: eight minus three?
(Example: nine)

The Note You're Voting On

fabmlk at hotmail dot com
10 years ago
If you ever need to open multiple distinct sessions in the same script and still let PHP generate session ids for you, here is a simple function I came up with (PHP default session handler is assumed):
<?php
/**
 * Switch to or transparently create session with name $name.
 * It can easily be expanded to manage different sessions lifetime.
 */
function session_switch($name = "PHPSESSID") {
 static $created_sessions = array();
 if (session_id() != '') { // if a session is currently opened, close it
 session_write_close();
 }
 session_name($name);
 if (isset($_COOKIE[$name])) { // if a specific session already exists, merge with $created_sessions
 $created_sessions[$name] = $_COOKIE[$name];
 }
 if (isset($created_sessions[$name])) { // if existing session, impersonate it
 session_id($created_sessions[$name]);
 session_start();
 } else { // create new session
 session_start();
 $_SESSION = array(); // empty content before duplicating session file
 // duplicate last session file with new id and current $_SESSION content
 // If this is the first created session, there is nothing to duplicate from and passing true as argument will take care of "creating" only one session file
 session_regenerate_id(empty($created_sessions));
 $created_sessions[$name] = session_id();
 }
}
session_switch("SESSION1");
$_SESSION["key"] = "value1"; // specific to session 1
session_switch("SESSION2");
$_SESSION["key"] = "value2"; // specific to session 2
session_switch("SESSION1");
// back to session 1
// ...
?>

When using this function, session_start() should not be called on its own anymore (can be replaced with a call to session_switch() without argument).
Also remember that session_start() sets a Set-Cookie HTTP header on each call, so if you echo in-between sessions, wrap with ouput buffering.
Note: it's probably rarely a good idea to handle multiple sessions so think again if you think you have a good use for it.
Personally it played its role for some quick patching of legacy code I had to maintain.

<< Back to user notes page

AltStyle によって変換されたページ (->オリジナル) /