Accessing two sessions in given PHP script

2019-07-24 19:52发布

问题:

The following script creates two cookies (SESSION1 and SESSION2), however, both contain the same session_id value.

How can I modify this script so that both sessions will be independent?

Thank you

<?php
$t=time();
session_name('SESSION1');
session_start();
$_SESSION['s1_'.$t]=$t;
echo('SESSION1<pre>'.print_r($_SESSION,1).'</pre>');
session_write_close();
$old_session=session_name('SESSION2');
session_start();
$_SESSION['s2_'.(2*$t)]=2*$t;
echo('SESSION2<pre>'.print_r($_SESSION,1).'</pre>');
session_write_close();
session_name($old_session);
session_start();
echo('SESSION1<pre>'.print_r($_SESSION,1).'</pre>');
?>

回答1:

You also need to change session ID for each new session. Try this:

$t=time();

session_name('SESSION1');
$s1 = session_id('ID1');
session_start();
$_SESSION['s1_'.$t]=$t;
echo('SESSION1<pre>'.print_r($_SESSION,1).'</pre>');
session_write_close();

$old_session = session_name('SESSION2');
$s2 = session_id('ID2');
session_start();
$_SESSION['s2_'.(2*$t)]=2*$t;
echo('SESSION2<pre>'.print_r($_SESSION,1).'</pre>');
session_write_close();

session_name($old_session);
session_id('ID1');
session_start();
echo('SESSION1<pre>'.print_r($_SESSION,1).'</pre>');