How to generate a unique session ID in php

On our websites we want to make it possible to share sessions accros multiple domains. All these websites are on the same server but some of them have a different IP address.

The possible solution I found was to set the session ID myself:

<?php
session_id($someUniqueHash);
?>

And this works, if I make the hash like md5('test'). On a other domain on te same server we have the session again.

The problem is generating the ID. I see some solutions on the internet with microtime etc, but when I use that approach I can't predict the session ID on the other domain / PHP page.

Does anyone have an idea? Or shouldn't we implement this? Are there other options to share session over multiple domains? (NOT subdomains!)


I've achieved this system by using an OAuth type flow but we replaced the Consumer with the User.

So each domain would have the authenticated Access_Token in its own session. You would then use that Access_Token to get information about user from an api.

I also solved the session problem using session_set_save_handler and storing sessions in a database table... This table would have the Access_Token also, making it really easy to find the session with a DB Query.

Hope this helps with ideas.


Hmm this is a difficult one.

As everyone knows PHP uses cookies to understand session_ids when a user comes back to your site and there is no way of cross domain cookies: Cross domain cookies (edit: there is but the method is complicated).

This is probably why I have never seen a site implement this even though they have different domains.

You could, via a link on your page from one domain pass the session id to the next domain through $_GET or $_POST. This will not work if the user directly enters your other site.

The only partially (no reliable) method I can come up with is to keep a record of the users comptuer in the DB and use that to understand what session is attached it to. So you house the computers IP address and maybe some other details and that backs onto a session.

The IP and other details of a persons computer would log them into the other domain.


Maybe this is not an option for you, but you could try this.

On your main site you generate the session id as per normal and to perpetuate the session to another domain you could include image tags with the session id in the URL. In response, the other domain will set a cookie, so that when the visitor comes there it will already know the session id.

Feels a bit smarty pants solution, but it should work if you don't have too many other domains :) third party cookies can be disabled separately in browsers btw, something to consider.

Oh btw, session adoption (accepting an id via query parameters and setting a cookie) is delicate stuff and should be protected, ie session must already exist before setting cookie.

链接地址: http://www.djcxy.com/p/60752.html

上一篇: VIM在回车中添加一个字符到换行符

下一篇: 如何在php中生成一个唯一的会话ID