-
Today, I ran into an issue while working on a project. Previously, when dealing with sessions, I would typically store them directly in the database, which solves cross-domain problems
— not just cross-subdomain ones. But today’s issue was different: I had to make modifications on top of someone else’s existing work. Since it only involved subdomains,
I was confident there had to be a simple solution. After Googling (Baidu-ing) for about 10 minutes, I got it sorted:
A session is mainly composed of two parts:
The first is the session data. By default, this data is stored in the server’s tmp directory as a file.
The second is the Session ID that identifies the session data. The Session ID is essentially the filename of that session file. It is randomly generated, ensuring uniqueness and randomness, which guarantees session security. Typically, if no session lifetime is set, the Session ID is stored in memory. Closing the browser invalidates the ID, and reloading the page will register a new Session ID. If the client has not disabled cookies, the cookie plays the role of storing the Session ID and the session lifetime when the session starts.
When two different domain websites want to use the same session, it becomes a session cross-domain problem!
By default, each server generates its own SESSION ID for the same client. For example, for the same user’s browser, server A generates SESSION ID 11111111111, while server B generates 22222222. Additionally, PHP session data is stored in each server’s local filesystem. To share session data, two goals must be achieved:
One: each server must generate the same SESSION ID for the same client, and it must be transmitted through the same cookie — meaning each server must be able to read the same PHPSESSID cookie. Two: the session data storage method/location must be accessible to all servers. In short, multiple servers (A, B) must share the client’s SESSION ID, and at the same time share the server-side session data.There are three solutions:
1. Simply add the following settings at the very beginning of the PHP page (before any output, and before session_start()):
ini_set('session.cookie_path', '/');ini_set('session.cookie_domain', '.mydomain.com');
ini_set('session.cookie_lifetime', '1800');
2. Set in php.ini
session.cookie_path = /
session.cookie_domain = .mydomain.comsession.cookie_lifetime = 1800
3. Call the function at the very beginning of the PHP page (same conditions as #1)
session_set_cookie_params(1800 , '/', '.mydomain.com');
My solution was to add the following code at the entry point:
ini_set('session.cookie_path', '/');
ini_set('session.cookie_domain', '.domain.com'); // Note: replace domain.com with your own domain
ini_set('session.cookie_lifetime', '1800');
As shown:
Site One
Site Two
You can see that the PHPSESSID is the same on both sites, so the cross-subdomain issue is naturally resolved.

