PHP Sessions across sub domains

前端 未结 17 1665
慢半拍i
慢半拍i 2020-11-22 05:59

I am trying to set up the following:

auth.example.com
sub1.example.com
sub2.example.com

If the user visits sub1.example.com or

17条回答
  •  迷失自我
    2020-11-22 06:13

    I have confirmed. joreon's answer is correct. I cannot comment because my reputation is not enough so I post my comment here.

    Define the constant in a config file. If you want to change it, no need to modify whole files.

    define('ROOT_DOMAIN',   'mysite.example');
    define('PHP_SESSION_NAME', 'MYSITE'); 
    

    The session name can't consist of digits only, at least one letter must be present. Otherwise, a new session id is generated every time.

    Use the following code to start using session

    session_name(PHP_SESSION_NAME);
    session_set_cookie_params(0, '/', '.' . ROOT_DOMAIN);
    session_start();
    

    I'm using this function:

    function load_session() {
        if (session_status() == PHP_SESSION_NONE) {
            session_name(PHP_SESSION_NAME);
            session_set_cookie_params(0, '/', '.' . ROOT_DOMAIN);
            session_start();
        } elseif (session_name() != PHP_SESSION_NAME) {
            session_destroy();
            session_name(PHP_SESSION_NAME);
            session_set_cookie_params(0, '/', '.' . ROOT_DOMAIN);
            session_start();
        }
    }
    load_session(); // put it in anywhere you want to use session
    

提交回复
热议问题