We all know that the session is not to cross the domain, that is to say: A.wemvc. COM This domain executable file can not access to the b.wemvc.com session, this is the characteristics of the session, but also for security reasons.
In general, a site has only one domain name, but there are also some Web site architectures that are organized by multiple subdomains. This requires that the session can be accessed across the subdomain, so that the user's Cross-domain logins can be implemented. That is, the client logged in under A, same b also logged in, do not require the user to log in again, The cross domain transfer of the parameters is also realized. Of course not the Cross-domain session itself has been able to help us do a lot of things, then the session after the Cross-domain. Is it exciting to read here, and you may also be finding this article for your session across the domain? Also congratulations to you. We have a long-distance call to start our course today: cookies and sessions are implemented with the session cross domain.
First let's review the cookies and session in PHP:
Cookies:
Defined:
Cookies are often used to identify users. Cookies are small files that the server leaves on the user's computer. Whenever the same computer requests a page through a browser, it sends cookies as well. With PHP, you can create and retrieve the value of a cookie. PS: Its Chinese name is "cookie".
Use the Setcookie function in PHP to set the cookie, which has 7 parameters (here I would like to apologize to one of my colleagues I interviewed, when I said the answer was 6, sorry~, and I also remind the General writers to update their articles as soon as possible, 7 parameters were added to the PHP5.2.0 version. The 7 parameters are string $name [, String $value [, int $expire [, String $path [, String $domain [, bool $s Ecure [, BOOL $httponly]]]].
nameThe name of the cookie. Specify the name of the cookie.
valueThe value of the cookie. This value was stored on the clients computer; Do not store sensitive information. Assuming thenameIs ' cookiename ', the This value is retrieved through $_cookie[' CookieName '] prescribes the value of the COOKIE.
expireThe time the cookie expires. This is a Unix timestamp and so are in number of seconds since the epoch. In a words, you'll most likely set this with theTime ()Function plus the number of seconds before you want it to expire. Or for might usemktime ().Time () +60*60*24*30Would set the cookie to expire in. If set to 0, or omitted, the cookie would expire at the "end of the" session (when the browser closes). Specify the expiration date of the cookie.
Note: Your may notice the
expire parameter takes on a Unix timestamp, as opposed to the date format C3>wdy, dd-mon-yyyy HH:MM:SS GMT, this are because PHP does this conversion internally.
expire is compared to the client's time which can differ from server ' s time.
PathThe path on the server in which the cookie is available on. If set to'/', the cookie would be available within the entireDomain. If set to'/foo/', the cookie would be available within the/foo/Directory and all sub-directories such as/foo/bar/OfDomain. The default value is the current directory, this cookie is being set in. Sets the server path for cookies.
SecureIndicates that the cookie should is transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie is only to be set if a secure connection exists. The default is FALSE. On the server-side, it's on the "programmer to send" this kind of cookies only in secure connection (e.g. with respect to$_server["HTTPS"]). Specify whether to transmit cookies through a secure HTTPS connection.
HttpOnlyWhenTRUEThe cookie is made accessible only through the HTTP protocol. This means the cookie won ' t is accessible by scripting languages, such as JavaScript. This setting can effectly help to reduce identity theft through XSS attacks (although it isn't supported by all browsers) . Added in PHP 5.2.0.TRUEOrFALSE. Specify whether access cookies must be defined through the HTTP protocol to prevent XSS attacks .
Session Full Course
The session here is not too much to explain, mainly:
session_cache_expire -return Current Cache expire
session_cache_limiter -get and/or set the current cache limiter
session_commit -alias of Session_write_close
Session_decode -decodes session data from a string
Session_destroy -destroys All data registered to a
Session_encode -encodes The current session data as a string
Session_get_cookie_params -get the session cookie parameters
session_id -get and/or set the current session ID
session_is_registered -find out whether a global variable are registered in a
session_module_name -get and/or set the current session module
session_name -get and/or set the current session name
session_regenerate_id -update The current session ID with a newly generated one
Session_register -register One or more global variables
Session_save_path -get and/or set the current session save path
Session_set_cookie_params -set the session cookie parameters
Session_set_save_handler -sets user-level Session storage functions
Session_Start -initialize session data
session_unregister -unregister A global variable from the
Session_unset -free All sessions variables
Session_write_close -write session data and end session
Haha, not my lazy oh, here is only about Cross-domain.
OK, probably brush up the next cookie and session, start to implement our Cross-domain.
First I describe my idea that a cookie can specify a domain name, meaning that it can cross domain subdomains, such as: Setcookie (' name ', ' Joshua ', Time () +3600*24, '/', ' wemvc.com '), then a.wemvc.com , b.wemvc.com can access the $_cookie[' name ' and the value is ' Joshua '. Similarly, the session ID can also be set to this domain name, So both a.wemvc.com and b.wemvc.com can get the same session ID, so our goal is achieved. Because you know the same session ID, you can access the value in this session. Sessions are stored in various ways, files \ database \ Memory, etc., we use database storage, because if the a.wemvc.com,b.wemvc.com is not on the same server, then memory and file storage way is difficult to achieve cross-domain, as for the end and no way, I have not tried.
First, create a session table in the database:
CREATE TABLE ' Sessions ' (
' SID ' varchar not NULL default ',
' expiry ' int unsigned not NULL default ' 0 ',
' Value ' text not NULL,
PRIMARY KEY (' Sid '),
KEY ' expiry ' (' expiry ')
) Engine=myisam DEFAULT Charset=utf8;
Then write a class that is used to read \ insert \ update \ Delete and garbage collection session
Class session{
Private $db;
function __construct ($db) {
$this->db= $db;
}
Public function open ($save _path, $session _name) {
return true;
}
Public function Close () {
$this->db=null;
return true;
}
Public function Read ($SID) {
$rs = $this->db->query ("SELECT * from sessions where sid= '". $sid. "");
foreach ($rs as $row) {
return $row [' value '];
}
return null;
}
Public function Write ($sid, $value) {
if (is_null ($oldvalue = $this->read ($sid)) {
Insert
return $this->db->query (insert INTO sessions (Sid,expiry,value) VALUES ('. $sid. "', '". Time (). "', '". $value. ");
}else{
Update
return $this->db->query ("Update sessions set expiry= '". Time (). "', value= '". $value. "' Where sid= '. $sid." ");
}
}
Public function Destroy ($SID) {
return $this->db->query ("Delete from sessions where sid=". $sid. "");
}
Public Function GC ($max _life_time) {
return $this->db->query (' Delete from sessions where expiry+ '. $max _life_time. ' < '. time ());
}
}
Let me explain this class:
Private $db; The database property of the class.
function __construct ($DB) class constructor, when declaring a class, you can directly pass the DB attribute to the class, of course, if you still do not understand the "PHP class construct method";
Public function open ($save _path, $session _name) session open, no flower head, return true directly;
The public Function close () session is closed, same as open, but note that you want to turn off the DB connection;
The public function read ($SID) session reads, passes the value SID, returns the value of this SID as the return value in the datasheet;
The Public function write ($SID, $value) writes and updates to the session, which you will have a question about, why set expiry= ' ". Time ()." ', the answer will be revealed in the GC method of the expired session later;
The destruction of the Destroy ($SID) session of the public function is simply the deletion of data in the data table that is equal to this SID;
The Public Function GC ($max _life_time) empties the expired session and destroys the session over Max_life_time, which means that the session creation time plus the maximum survival time is less than the present time (expiry+ '. $max _life_time. ' The session data for the < '. Time ()) is deleted, so you can see why the current time is written in the method of writing and updating the session, of course, the writing is not absolute, as long as your SQL is written correctly.
Okay, let's move on to the more important part:
The above class requires a database link attribute, so you need to declare the object:
$session =new session (your DB connect adapter);
Database links I can provide you with a PDO method, refer to the use of:
function connect_db ($arrPDODB) {
$db =new PDO ($arrPDODB [' db_driver ']. ': host= '. $arrPDODB [' Db_host ']. Dbname= '. $arrPDODB [' db_name '], $arrPDODB [' Db_user '], $arrPDODB [' Db_password ']);
$db->query ("Set names ' utf8′");
return $db;
}
So, the above declaration object section you can write like this:
$session =new session (connect_db ($arrPDODB));
Next:
Sets the name of the color session ID
Ini_set (' session.name ', ' Sid ');
Do not use the Get/post variable method
Ini_set (' Session.use_trans_sid ', 0);
Set maximum lifetime for garbage collection
Ini_set (' Session.gc_maxlifetime ', 3600);
How to save session IDs with cookies
Ini_set (' session.use_cookies ', 1);
Ini_set (' Session.cookie_path ', '/');
Multi-host sharing cookies that hold the session ID, note that the domain name is a first-level domain name
Ini_set (' Session.cookie_domain ', ' wemvc.com ');
Set the Session.save_handler to user instead of the default files
Session_module_name (' user ');
Session_set_save_handler (Array ($session, ' open '),
Array ($session, ' close '),
Array ($session, ' read '),
Array ($session, ' write '),
Array ($session, ' destroy '),
Array ($session, ' GC '));
The above is the setting of the session, do not understand more search under the manual, I like inquisitive study the end of this way of learning, so you can learn a knowledge point, rather than know a little, think oneself understand or will.
Finally, start the session where you need it:
Session_Start ();
Finally, we provide a how to prevent session forgery attacksBlog, hoping to read it carefully.
OK, well, as long as you have this class in front of each executable file and start it, your program can be cross-domain, hehe. You can also cross domain domain names. You can write it down for me a blog postLet's study it before myself.
In addition, to say first, in fact Ajax can also cross subdomains, then give me the next article BowenTo pave the ground. Haha, welcome everyone to discuss with me to study together.
September 26, 2008 Update:
Added a demo program, the program is very simple, did not write the storage of things, suitable for beginners to learn.
Report:
demo_session_1
Program Explanation: Very simple a B two folders to represent you two domains, your virtual machine set to A.yourdomain.com, b.yourdomain.com on it. First of all understand this, and then consider the session of the warehousing things. Session storage is mainly because a site has more than one server, if the session or the default file type to save, multiple servers is not workable.
demo_session 2
Program Explanation: This program adds the warehousing function, the data table creation, the file has above.