PHP cross-domain, cross-subdomain, read session across servers

Source: Internet
Author: User
Tags ip number session id setcookie tmp file subdomain

1. Cross-domain and cross-server solutions

The session is divided into two main parts:
One is session data, which is stored in the server's TMP file by default, and is in the form of a file
The other is the session Id,session ID that indicates session data, that is, the file name of the session file, the session Id is randomly generated, so it can guarantee uniqueness and randomness, ensure the security of the session. In general, if the lifetime of the session is not set, the session ID is stored in memory, the ID is automatically logged off after the browser is closed, and a session ID is re-registered after the page is re-requested. If the client does not disable cookies, the cookie plays the role of storing the session ID and session lifetime when the session is started.

Two different domain name website, want to use the same session, is involved in the session cross-domain problem!
By default, each server generates SESSIONID for the same client individually, for example, for the same user browser, the SESSION ID generated by a server is 11111111111, while the B server generates 222222. In addition, the session data of PHP is stored separately in the file system of this server. To share SESSION data, you must achieve two goals:
One is that each server generates the same session ID for the same client and can be passed through the same cookie, which means that each server must be able to read the same cookie named Phpsessid, and the other is how the session data is stored The location must ensure that each server has access to it. These two goals are simply the session ID of the multi-server (A, b Server) shared client, and must also share the session data on the server side.
The implementation of the first goal is very simple, only the domain of the cookie must be specifically set (the Setcookie () function of the 4th parameter), by default, the domain of the cookie is the domain name/IP address of the current server, and the domain is different , the cookies set by each server are not accessible to each other,

1) Cross-subdomain

In this way, cross-domain does not work, but the same subdomain can, such as: and belong to the domain. is OK, then we can set the COOKIE domain to., so,, and so on can access this cookie. The purpose of each server sharing the same client SESSION ID is achieved.

Implemented as follows


There are three ways to achieve this:

1. The following settings are provided at the beginning of the PHP page (to be preceded by any output and before session_start ())

Ini_set (' Session.cookie_path ', '/');
Ini_set (' Session.cookie_domain ', '. ');
Ini_set (' Session.cookie_lifetime ', ' 1800 ');

2. Set in php.ini

Session.cookie_path =/
Session.cookie_domain =.

Session.cookie_lifetime = 1800

3. Call the function at the beginning of the PHP page (condition same as 1)

Session_set_cookie_params (1800, '/', '. ');

These three ways are the same effect.

Here I set the first method, respectively, in and two domain names to test, the test code is as follows



First visit the page to do the setup

Ini_set (' Session.cookie_path ', '/');
Ini_set (' Session.cookie_domain ', '. ');
Ini_set (' Session.cookie_lifetime ', ' 1800 ');


Session_set_cookie_params (1800, '/', '. ');
Session_Start ();
$_session[' sub1 '] = ' sub1 ';
Print_r ($_session);




Session_set_cookie_params (1800, '/', '. ');
Session_Start ();
$_session[' sub2 '] = ' sub2 ';
Print_r ($_session);


Access Order:


Page output: Array ([sub1] = sub1)


Page output: Array ([sub1] = sub1 [SUB2] = sub2)



The second target implementation can use the database to save session data, so that each server can easily access the same data source, get the same session data, or through file sharing, such as NFS (my other articles have how to configure NFS)
If you use the database to store SESSION data, there may be a legacy problem, that is, if the site is a large number of visits, session read and write will be frequently on the database operation, you can put this in the memcache. stored in the database in front of the article has been implemented. The idea of combining databases with Memcache is in front of them. If it is not very good to store the session alone with Memcache, it is best to combine with the database.

2) cross-domain resolution

Idea: The IFRAME is resolved, but FF is not supported, so it needs to be preceded by the P3P protocol.

P3P (Platform for Privacy Preferences Project), simply put, is a protocol that declares it to be a good person, allowing me to collect browser user behavior ... But in reality, everyone can say that they are good people, secretly maybe do what bad things. This is where the differences lie. [Reference] Most of the domestic sites, are not concerned about this P3P. Privacy issues may not be valued abroad (Microsoft's privacy statement).

The first thought is to operate the cookie through JS and let two different domains of cookies can access each other, so that can achieve the above effect, the specific implementation process can be divided into the following two steps:

1, after the successful login in a system, using JS dynamic Create a hidden iframe, through the SRC attribute of the IFRAME, the cookie value under a domain is redirected to the b.jsp page under the B system as a get parameter;

[JavaScript]View Plaincopyprint?
    1. var _frm = document.createelement ("iframe");
    3. _FRM.SRC = "";//here XXX Best code
    4. Document.body.appendChild (_FRM);

2, in the setcookie.php page of the B system to obtain the value of the cookie passed in a system, and the obtained value is written to the user's cookie, of course, the domain is their own, so that the simple implementation of the cookie cross-domain access; But there is one problem to be aware of, is in IE browser such operation can not succeed, need to set P3P HTTP header in the setocokie.php page can be solved (detailed information can refer to:, the P3P setup code is:Header (' p3p:cp= ' CURa ADMa DEVa Psao psdo our BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR "');//ecshop so set the above CP code Meaning cura
Information is used to complete the activity for which it was provided.

Information may is used for the technical, the WEB site and its computer system.

Information may is used to enhance, evaluate, or otherwise review the site, service, product, or market.

Information may used to create or build a record of a particular individual or computer that's tied to a pseudonymous identifier, without tying identified data (such as name, address, phone number, or email address) to the record. This profile would be used to determine the habits, interests, or other characteristics of individuals for purpose of RESEA RCH, analysis and reporting, but it'll is not being used to attempt to identify specific individuals.

Information may used to create or build a record of a particular individual or computer that's tied to a pseudonymous identifier, without tying identified data (such as name, address, phone number, or email address) to the record. This profile would be used to determine the habits, interests, or other characteristics of individuals for make a decision T Hat directly affects that individual, but it'll not be used to attempt to identify specific individuals.

We share information with ourselves and/or entities acting as our agents or entities for whom we is acting as an agent.

Info is retained under a service provider ' s stated business practices. Sites must has a retention policy that establishes a destruction time table. The retention policy must is included in or linked from the site ' s human-readable Privacy policy.

non-financial identifiers, excluding government-issued identifiers, issued for purposes of consistently identifying or rec Ognizing the individual. These include identifiers issued by a Web site or service.

Information actively generated by the purchase of a product or service, including information is about the method of payment.

Data actively generated from or reflecting explicit interactions with a service provider through its site--such as Queri Es to a search engine, or logs of the account activity.

Data about an individual ' s characteristics--such as gender, age, and income.

Mechanisms for maintaining a stateful session with a user or automatically recognizing the WHO has visited a particular Site or accessed particular content previously--such as HTTP cookies.

Data about an individual ' s likes and dislikes--such as favorite color or musical tastes.

Information about the computer system, the individual are using to access the network--such as the IP number, domain Name, browser type or operating system.

Data passively generated by browsing the WEB site--such as which pages is visited, and how long users stay on each page .

Other types of data is captured by the above definitions.

Web Site does not collected identified data.

The privacy policy contains disputes elements.

Errors or wrongful actions arising in connection with the privacy policy would be remedied by the service.

Validate at:
Learn More At:

PHP cross-domain, cross-subdomain, read session across servers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.