PHP How can I create multiple sessions?

后端 未结 2 1905
刺人心
刺人心 2020-12-03 02:02

I want to be able to switch back and forth between sessions in php. Here is my current code:



        
2条回答
  •  隐瞒了意图╮
    2020-12-03 02:28

    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:

    ", print_r($_SESSION, 1), "
    "; session_write_close(); sane_session_name("session2"); session_start(); $_SESSION["name"] = "2"; echo "
    ", print_r($_SESSION, 1), "
    "; session_write_close(); sane_session_name("session1"); session_start(); echo "
    ", print_r($_SESSION, 1), "
    ";

    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:

    ", print_r($_SESSION, 1), "
    "; session_write_close(); sane_session_start("session2"); $_SESSION["name"] = "2"; echo "
    ", print_r($_SESSION, 1), "
    "; session_write_close(); sane_session_start("session1"); echo "
    ", print_r($_SESSION, 1), "
    ";

提交回复
热议问题