I want to share my session variables in PHP using many subdomains. I have that example :
I try to use the same session variables between the two domains. I already tested a lot of functions in PHP but nothing work. Here is my way to test :
On the example.com/page.php, I have that test :
echo '<pre>';
var_dump(session_set_cookie_params(0, '/', '.example.com'));
session_start();
echo "Session ID : ".session_id()."\n";
$_SESSION['foo'] = 'bar';
print_r($_SESSION);
And on subdomain1.example.com/page.php, I have that one :
echo '<pre>';
session_set_cookie_params(0, '/', '.example.com');
session_start();
echo "Session ID : ".session_id()."\n";
print_r($_SESSION);
I can see that the session id is the same between the two pages, but session variables are impossible to read in subdomain1.example.com/page.php
I tested many functions, like set a name to the session, but with no more results.
Thank you.
The only way I can think of to do this would be to save the session data to a cookie, then open the cookie when the other domain is accessed. You can read how to do this here: http://www.depiction.net/tutorials/php/cookies-session-variables.php
Out of curiosity, why do you want to do this?
If you want to avoid using a cookie based solution, and both domains can access the same database, I'd be storing the session in the database instead of the filesystem:
Here's an exmaple in the comments for the session at php.net: http://php.net/manual/en/book.session.php
If storing in a cookie is not possible, you can use a shared cache layer. This can be a database such as MySQL, or even use an APC (if it's being served by the same server). You can also use memcache. Memcache based sessions are faster than using a database. More information on the memcache session store can be found here:
The following code is tested and working, without the requirement for direct cookie manipulation (other than the session itself), or anything complex like Memcache/DB storage.
ini_set('session.cookie_domain', '.sonassi.com' );
session_name('sonassi');
session_start();
Just make sure that the session_save_path
is accessible by both domains.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.