PHP cross-domain, cross-domain, cross-server read session

Source: Internet
Author: User
Tags ip number tmp file in domain subdomain
1. Cross-Domain and cross-server solutions

Sessions are divided into two parts:
One is Session data, which is stored in the tmp file of the server by default and exists as a file
The other is the Session Id of the Session data. The Session ID is the name of the Session file. The Session ID is generated randomly. Therefore, the uniqueness and randomness can be ensured to ensure the security of the Session. Generally, if the Session life cycle is not set, the Session ID is stored in the memory. When the browser is closed, the ID is automatically deregistered. After the page is requested again, a session ID is re-registered. If the client does not disable the Cookie, the Cookie stores the Session ID and
The role of the Session.

If you want to use the same Session for two different domain name websites, the cross-domain Session issue is involved!
By default, each server generates a session id for the same client. For example, for the same user browser, the session id generated by server A is 11111111111, server B generates 222222. In addition, the SESSION data of PHP is stored in the file system of the current server. To share SESSION data, you must achieve the following two goals:
One is that the SESSION IDs generated by each server on the same client must be the same and can be passed through the same COOKIE. That is to say, each server must be able to read the same phpsessid cookie; the other is the storage mode/location of SESSION data, which must be accessible to all servers. The two goals are simply to share the session id of the client with multiple servers (server A and server B) and the SESSION data of the server.
First goalThe implementation is actually very simple. You only need to set the cookie domain (4th parameters in the setcookie () function). By default, the cookie domain is the domain name/IP address of the current server. If the domain is different, the cookies set by each server cannot access each other,

1) Cross-subdomain

In this way, cross-origin is not feasible, but the same subdomain can be used. For example, aaa.cocoglp.com and www.cocoglp.com both belong to the domain .cocoglp.com, so we can set the cookie domain to .cocoglp.com.
Aaa.cocoglp.com and www.cocoglp.com can all access this cookie. In this way, each server shares the same client session ID.

The implementation is as follows:

Bytes -------------------------------------------------------------------------------------------------

There are three methods to achieve this:

1. Make the following settings at the 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 ', '123 ');

2. Set in PHP. ini

Session. cookie_path =/
Session. cookie_domain = .mydomain.com

Session. cookie_lifetime = 1800

3. Call the function at the beginning of the php page (condition 1)

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

These three methods have the same effect.


Here I use the first method to set up and test the domain names www.mydomain.com and sub.mydomain.com respectively. The test code is as follows:

Sub1.php

<? Php

// Configure the first accessed page

Ini_set ('session. cookie_path ','/');
Ini_set ('session. cookie_domain ',' .mydomain.com ');
Ini_set ('session. cookie_lifetime ', '123 ');

//

Session_set_cookie_params (1800, '/', '.mydomain.com ');
Session_start ();
$ _ SESSION ['job1'] = 'job1 ';
Print_r ($ _ SESSION );

?>

Sub2.php

<? Php

Session_set_cookie_params (1800, '/', '.mydomain.com ');
Session_start ();
$ _ SESSION ['sub2'] = 'sub2 ';
Print_r ($ _ SESSION );

?>


Access sequence:

(1) www.mydomain.com/sub1.php

Page output: Array ([sub1] => sub1)

(2) sub.mydomain.com/sub2.php

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

Successful

Bytes ----------------------------------------------------------------------------------------------------


Second goalThe database can be used to save SESSION data, so that each server can easily access the same data source and obtain the same SESSION data; or, through file sharing, for example, NFS (how to configure nfs in other articles)
If you use a database to store session data, there may be a legacy problem, that is, if the website has a large amount of traffic, SESSION reads and writes will frequently perform database operations, you can put this in memcache. It is implemented in the previous article in the database. The idea of combining databases with memcache is now available. If it is not good to use memcache to store sessions separately, it is best to work with the database.

2) Cross-origin Solution

Idea: Use iframe, but ff does not support it. Therefore, you need to add the p3p protocol.

P3P (Platform for Privacy Preferences Project), simply put, is a protocol, through which it is declared as a good person, allow me to collect browser user behavior... but in reality, everyone can say that they are good people, and they may not be doing anything bad in the back. This is where their differences are. [Reference]
Most websites in China do not pay attention to this P3P. Privacy issues may not be valued abroad (Microsoft's privacy statement.

The first thought is to use JS to operate the Cookie and allow the cookies of two different domains to access each other, so that the above effect can be achieved. The specific implementation process can be roughly divided into the following two steps:

1. After successfully logging on to system A, use js to dynamically create a hidden IFRAME, use the src attribute of IFRAME to redirect the cookie value in Domain A to system B as the get parameter. JSP page;

VaR _ FRM = Document. createelement ("iframe"); _ frm. style. Display = "NONE"; _ frm. src = "http://www.222.com/setcookie.php? Mycookie = XXXXX "; // here XXX is best encoded as document. Body. appendchild (_ FRM );

2. setcookie in system B. on the PHP page, obtain the cookie value passed in system A and write the obtained value to the user's cookie. Of course, the domain is your own, in this way, the cross-origin access of cookies is implemented. However, you must note that this operation cannot be successful in IE, and you need to perform this operation in setocokie. set p3p on the PHP page
HTTP header can be solved (For details, refer to: http://www.w3.org/P3P/), p3p set the code to: Header ('p3p: CP = "Cura ADMA Deva psao psdo our bus uni pur int DEM sta pre com nav OTC Noi DSP cor" '); // ecshop this setting
The meaning of the above CP code
Cura
Information is used to complete the activity for which it was provided.

ADMA
Information may be used for the technical support of the web site and its computer system.

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

PSAo
Information may be used to create or build a record of a particle individual or computer that is tied to a pseudo donymous identifier, without tying identified data (such as name, address, phone number, or email address) to the record. this profile will be used
To determine the habits, interests, or other characteristics of individuals for purpose of research, analysis and reporting, but it will not be used to attempt to identify specific individuals.

PSDo
Information may be used to create or build a record of a particle individual or computer that is tied to a pseudo donymous identifier, without tying identified data (such as name, address, phone number, or email address) to the record. this profile will be used
To determine the habits, interests, or other characteristics of individuals to make a demo-that directly affects that individual, but it will not be used to attempt to identify specific individuals.

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

BUS
Info is retained under a service provider's stated business practices. sites MUST have a retention policy that establishes a destruction time table. the retention policy MUST be pinned in or linked from the site's human-readable privacy policy.

UNI
Non-financial identifiers, excluding government-issued identifiers, issued for purposes of consistently identifying or recognizing the individual. These include identifiers issued by a Web site or service.

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

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

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

STA
Mechanic ISMs for maintaining a stateful session with a user or automatically recognizing users who have visited a particle site or accessed particle content previusly -- such as HTTP cookies.

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

COM
Information about the computer system that the individual is using to access the network -- such as the IP number, domain name, browser type or operating system.

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

OTC
Other types of data not captured by the above definitions.

NOI
Web Site does not collected identified data.

DSP
The privacy policy contains DISPUTES elements.

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

Validate at: http://www.w3.org/P3P/validator.html
Learn more: http://www.fiddlertool.com/redir? Id = p3pinfo

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: info-contact@alibabacloud.com 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.