As the comments to the existing answer indicate, the offered solution might not be ideal and I would like to provide some alternative. Let it be a function named sane_session_name()
, which looks like this:
function sane_session_name($name)
{
session_name($name);
if(!isset($_COOKIE[$name]))
{
$_COOKIE[$name] = session_create_id();
}
session_id($_COOKIE[$name]);
}
By using the "sane" subsitution for session_name()
in the OP's original code, we get this:
<?php
sane_session_name("session1");
session_start();
$_SESSION["name"] = "1";
echo "<pre>", print_r($_SESSION, 1), "</pre>";
session_write_close();
sane_session_name("session2");
session_start();
$_SESSION["name"] = "2";
echo "<pre>", print_r($_SESSION, 1), "</pre>";
session_write_close();
sane_session_name("session1");
session_start();
echo "<pre>", print_r($_SESSION, 1), "</pre>";
and it will yield the desired output:
Array
(
[name] => 1
)
Array
(
[name] => 2
)
Array
(
[name] => 1
)
What is different?
To point out the difference between this answer and the raidenace's answer:
- In raidenace's answer two sessions are created for all clients shared among all visitor of the website.
- With this answer two sessions are created for each visitor to the website. Consequently this would allow that in the
$_SESSION
superglobal different content can be stored for visitor Alice and Bob, while in the other two website visitor Alice an Bob would "share the data", and rather pointlessly a cookie named PHPSESSID
with the value session2 is set each time and send back and forth.
Security
To protect those "multiple (per user) sessions" from session fixation and session hijacking, we can further use this litte function
function sane_session_start($name)
{
ini_set("session.use_strict_mode",true);
ini_set("session.cookie_httponly",true);
session_name($name);
if(!isset($_COOKIE[$name]))
{
$_COOKIE[$name] = session_create_id();
}
session_id($_COOKIE[$name]);
session_start();
session_regenerate_id(true);
$_COOKIE[$name] = session_id();
}
and have the OP's code look like this:
<?php
sane_session_start("session1");
$_SESSION["name"] = "1";
echo "<pre>", print_r($_SESSION, 1), "</pre>";
session_write_close();
sane_session_start("session2");
$_SESSION["name"] = "2";
echo "<pre>", print_r($_SESSION, 1), "</pre>";
session_write_close();
sane_session_start("session1");
echo "<pre>", print_r($_SESSION, 1), "</pre>";
session_start();
only. – Yuuswitch()
along with conditional statements. php.net/manual/en/control-structures.switch.php – Yuudeveloperwjk
and in my comment. Plus,switch()
allows you more control along with conditional statements. – Yuu