PHP Sessions across sub domains

前端 未结 17 1484
慢半拍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:15

    I have read all answers above, I think my answer is helpful for people googling this:

    • make sure the browsers send session cookie back to servers (of domain and sub-domains), set session cookie domain as .example.com.

    • Make sure PHP find the right "target" to restore the session variable:

      • If domain and subdomains point to the same machine (maybe different virtual hosts), make sure session_save_path is the same for all (I tested)
      • If domain and subdomains point to different machines, the common storage (like database) is best for saving and restoring session data (I didn't test yet). Use session_set_save_handler to do that.
    0 讨论(0)
  • 2020-11-22 06:18

    I had a similar problem, however, this solution was good for me, perhaps will help others in the future

    edit the php.ini

    session.cookie_domain = ".example.com"

    the magic is here

    suhosin.session.cryptdocroot = Off
    
    suhosin.cookie.cryptdocroot = Off
    

    https://www.sitepoint.com/community/t/sessions-across-subdomains-domain-com-phpsessid-changes/3013/19

    0 讨论(0)
  • 2020-11-22 06:20

    Use it on every domain/subdomain:

    session_name('name');
    ini_set('session.cookie_domain', '.example.com');
    ini_set('session.save_path', '/var/lib/php/session');
    session_start();
    

    Path for session.save_path can be different for your case but it should be the same on every domain/subdomain. It is not always true by default.

    0 讨论(0)
  • 2020-11-22 06:26

    Use :

    session_name("put_a_session_name");
    session_start([
      "cookie_domain" => ".example.com",
      "cookie_path" => "/"
    ]);
    
    0 讨论(0)
  • 2020-11-22 06:27

    I solved it like this

    ini_set('session.cookie_domain', '.testdomain.example');
    session_start();
    

    Because I was working on localhost

    ini_set('session.cookie_domain', '.localhost');
    

    wasn't working, it sees .localhost as the toplevel instead of .com/.local/... (I suspect)

    0 讨论(0)
  • 2020-11-22 06:27

    Simply try using following code just above session_start() method

    $sess_life_time = 21600; //in seconds
    $sess_path = "/";
    $sess_domain = ".example.com";
    $sess_secure = true; // if you have secured session
    $sess_httponly = true; // httponly flag
    
    session_set_cookie_params($sess_life_time, $sess_path, $sess_domain, $sess_secure, $sess_httponly);
    
    0 讨论(0)
提交回复
热议问题