PHP session detailed analysis

Source: Internet
Author: User
Tags php session

2.7How to delete a session

(1) unset ($ _ session ['xxx']) deletes a single session. unset ($ _ session ['xxx']) is used to unregister a registered session variable. It works the same as session_unregister. Session_unregister () is no longer used in PhP5 and can be used in the Cold palace.
Unset ($ _ Session) is not available. It destroys the global variable $ _ session and there is no feasible way to restore it. You can no longer register the $ _ session variable.

(2) $ _ session = array () delete multiple sessions

(3) session_destroy () ends the current session and clears all resources in the session. This function does not unset the global variables related to the current session, nor delete the session cookies of the client. the default session of PHP is Cookie-based. to delete a cookie, you must use the setcookie () function.

The following is an official PHP case concerning session deletion:
<? PHP
// Initialize the session.
Session_start ();
/*** Delete all session variables .. You can also delete unset ($ _ session [XXX]) one by one. ****/
$ _ Session = array ();
/*** Delete sessin ID. Because session is based on cookie by default, setcookie is used to delete the cookie containing session ID .***/
If (isset ($ _ cookie [session_name ()]) {
Setcookie (session_name (), '', time ()-42000 ,'/');
}
// Finally, the session is completely destroyed.
Session_destroy ();
?>

The procedure for deleting a session is as follows:
① Session_start ()
② $ _ Session = array ()/unset ($ _ session ['xxx'])
③ Session_destroy ()

3.Cross-page session transfer:

3.1There are two ways to pass a session ID:Cookie URL parameters

The session module supports these two methods. Cookies are more optimized, but they are not always available and provide alternative methods. The second method directly embeds the session ID in the middle of the URL.

PHP can transparently convert links between pages. If you use a version earlier than PhP 4.2, You need to manually activate it when compiling PHP. in UNIX, use the -- enable-trans-Sid configuration option. If this configuration option and the runtime option session. use_trans_sid are activated (modify PHP. INI), The URI will be automatically changed to include session ID.

Note: A non-relative URL is assumed to point to an external site, so no Sid is appended, because this may be a security risk that the SID is leaked to different servers.

You can also use constants.Sid. If the client does not send a session cookieSidThe format isSession_name = session_idOtherwise, it is an empty string. Therefore, it can be embedded into the URL unconditionally.

3. 2 three ways to solve the cross-page session Transfer Problem
① Cookie is disabled on the client.
② The browser is faulty and the cookie cannot be accessed temporarily
③ Session. use_trans_sid = 0 in PHP. ini or the -- enable-trans-Sid option is not enabled during compilation.

When the cookie on the client is disabled or a problem occurs, PHP automatically attaches the session ID to the URL, so that the session variable can be used across pages through the session ID. However, this attachment also has certain conditions: "session. use_trans_sid = 1 in PHP. ini or the -- enable-trans-Sid option is enabled during compilation ";

After understanding the above principles, we can come up with three ways to solve the cross-page session transfer problem:
1. Set session. use_trans_sid = 1 in PHP. ini or enable the -- enable-trans-Sid option when compiling, so that PHP can automatically pass the session ID across pages.

(Some people say: but during the test, modify PHP. which method does ini use header ('location: XX. PHP ') and JavaScript window. location = xx. PHP does not achieve the desired effect. Currently, <a href = 'xx. php'> XX </a> is normal .)
2. Manually pass session IDs through URL values and hidden forms.
3. Save session_id in the form of files and databases, and manually call it during the cross-page process.
The following is an example:
First case:
Page1.php
<? PHP
Session_start ();
$ _ Session ['var1'] = "People's Republic of China ";
$ Url = "<a href =". "\" s2.php \ "> next page </a> ";
Echo $ URL;
?>
Page2.php
<? PHP
Session_start ();
Echo "the value of the passed session variable var1 is:". $ _ session ['var1'];
?>
Run the above Code. When the client cookie is normal, you can obtain the result "People's Republic of China ".
Now you can manually close the client cookie and run it again. The result may not be returned. If no result is returned, "set session. use_trans_sid = 1 in PHP. ini or enable the -- enable-trans-Sid option when compiling". The "People's Republic of China" is returned"

The second approach:
S1.php
<? PHP
Session_start ();
$ _ Session ['var1'] = "People's Republic of China ";
$ Sn = session_id ();

// PhP5 defines a constant Sid to represent session_id (). $ URL can also be written as $ url = '<a href = "page2.php? '. Sid.' "> next page </a> ';

$ Url = "<a href =". "\" s2.php? S = ". $ SN." \ "> next page </a> ";

Echo $ URL;
?>

S2.php

<? PHP
Session_id ($ _ Get ['s ']);
Session_start ();
Echo "the value of the passed session variable var1 is:". $ _ session ['var1'];
?>

Third approach:
Login.html
<! DoctypeHtmlPublic "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> login </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = ?????? ">
</Head>
<Body>
Please log on:
<Form name = "login" method = "Post" Action = "mylogin1.php">
Username: <input type = "text" name = "name"> <br>
Command: <input type = "password" name = "pass"> <br>
<Input type = "Submit" value = "login">
</Form>
</Body>
</Html>

Mylogin1.php

<? PHP
$ Name = $ _ post ['name'];
$ Pass = $ _ post ['pass'];
If (! $ Name |! $ Pass ){
Echo "the user name or password is empty. Please <a href = \" login.html \ "> log on again </a> ";
Die ();
}
If (! ($ Name = "laogong" & $ pass = "123 ")){
Echo "the user name or password is incorrect. Please <a href = \" login.html \ "> log on again </a> ";
Die ();
}
// Register a user
Ob_start (); // turn on output buffering
Session_start ();
$ _ Session ['user'] = $ name;
$ Psid = session_id ();
$ Fp = fopen ("E: \ TMP \ phpsid.txt", "W + ");
Fwrite ($ FP, $ psid );
Fclose ($ FP );
// Complete the authentication.
Echo "logged on <br> ";
Echo "<a href = \" mylogin2.php \ "> next page </a> ";
?>

Mylogin2.php
<? PHP
$ Fp = fopen ("E: \ TMP \ phpsid.txt", "R ");
$ SID = fread ($ FP, 1024 );
Fclose ($ FP );
Session_id ($ Sid );
Session_start ();
If (isset ($ _ session ['user']) & $ _ session ['user'] = "laogong "){
Echo "logged on! ";
}
Else {
// Log on successfully for related operations
Echo "not logged on, not authorized to access ";
Echo "Please <a href = \" login.html \ "> log on </a> and browse ";
Die ();
}
?>

4.Solution to sharing the same session with multiple servers

Websites with a slightly larger size usually have several servers. Each server runs modules with different functions and uses different second-level domain names. The user system of a website with a strong integrity is unified, that is, a user name and password can be used to log on to each module of the entire website. Sharing user data between servers is easy to implement. You only need to set up a database server on the backend. Each server can access user data through a unified interface. However, there is still a problem, that is, the user still needs to log on again after logging on to the server and entering another module of the server. This is a logon and all traffic problems, ing to the technology is actually how each server implements a shared session
Data problems.

To share session data, you must achieve two goals: one is that the session IDs generated by each server on the same client must be the same and can be transmitted through the same cookie, that is to say, each server must be able to read the same cookie named PHPSESSID; the other is the session data storage method/location, which must be accessible to each server. Simply put, multiple servers share the session ID of the client, and must also share the session data of the server.

The implementation of the first target is actually very simple. You only need to set the cookie domain. 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, for example
The server www.aaa.com cannot read or write data.
The cookie set by the www.bbb.com server. The servers of the same website have their own particularity, that is, they belong to the same level-1 domain, such as aaa.infor96.com and
Www.infor96.com all belong to the domain .infor96.com, so we can set the cookie domain to .infor96.com so that aaa.infor96.com and www.infor96.com can access this cookie. The setting method in PHP code is as follows:

Code:

Ini_set ('session. cookie_domain ',' .infor96.com ');

The implementation of the second target can use the file sharing method, such as the NFS method, but the settings and operations are somewhat complicated. We can refer to the previous method of unified user system, that is, using a database to save session data, so that each server can easily access the same data source and obtain the same session data.

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.