PHP authentication with multiple domains and subdomains

后端 未结 3 1813
有刺的猬
有刺的猬 2020-11-30 11:34

I have one main domain: main.com, subdomains: test1.main.com, test2.main.com and other domains one.com, two.com

相关标签:
3条回答
  • 2020-11-30 12:04

    To keep your sessions going across multiple domains, you need to use session_set_cookie_params(). With that, you can specify your domain. For example...

    session_set_cookie_params(10000, "/", ".main.com");
    

    That will set the session timeout at 10,000 seconds for all documents under the site root, and for all subdomains of main.com.

    You should call session_set_cookie_params() before you do session_start().

    0 讨论(0)
  • 2020-11-30 12:11

    As far as I know, crossing sessions between sub-domains is fine, but it won't carry over to a whole new domain. To do that you need some sort of centralized data method, or an API.

    Database method: you will have to create a remote MySQL data access so that domain2.com can access the database on domain1.com. When a log-in is performed, not only should it create a new session, but a unique log-in token (with an expiry time) should be put into the mysql database. Now, for every link that goes from domain1.com to domain2.com, you should add a $_GET variable that contains a randomly generated session id (md5 hash will do). domain2.com, upon receiving the visitor, will take the $_GET variable, run it through the MySQL database to find the login token, and if there is a match, consider that user to be logged on (and perhaps embed a $_COOKIE as well to store the login data). This will make the log-in transferrable between two completely different domains.

    API method: you need to create an API method, so that domain1.com can respond to an external request from authorized domains to retrieve the login token upon a user being forwarded. This method will also require that all links going from domain1.com to domain2.com to be appended with a $_GET variable to pass the unique session hash. Then upon receiving the visitor, domain2.com will do a curl() request to domain1.com/userapi.php (or whatever you call the file) and the variables should be tested against what's in the database.

    This is the best I can explain it.. to write this out in code is a significant piece of work so I cannot commit. But judging by your code, you have a very good understanding of PHP so I'm confident you will pull this off!

    Good luck mate.

    0 讨论(0)
  • 2020-11-30 12:19

    But if user reach domains one.com directly, than one.com can't know if user had login by the right answer mentioned above, seems like must use some extra js, it's jsonP! we let account.main.com/userLoginStat.php?callback=loginThisDomain to check if user had login main.com, if so, the js callback function loginThisDomain do some thing to autologin user to one.com.

    0 讨论(0)
提交回复
热议问题