PHP session detailed analysis

Source: Internet
Author: User
Tags define session php session

1. How PHP session works
The Session file is stored on the server. By default, the Directory of the SESSION file is specified by session. save_path. The file name is prefixed with sess _ and followed by session id, for example, sess_c000065af28a8b14c0fe11afe3b59b51b. You can obtain the user's file according to the session id provided by the client and get the variable value. The session id can use the Cookie of the client or Query_String of the Http1.1 protocol (that is, the "?" of the accessed URL To the server, and then the server reads the Session directory. That is to say, session id is used to obtain the id card of the session variable stored in the service.
When the code session_start (); is run, a session file is generated on the server, and a session id corresponding to it is also generated, define session variables to be stored in the generated session file in a certain form. The session id can be used to retrieve the Defined variables. After a cross-page session, you must execute session_start (); a session file is generated, and the corresponding session id is generated, this session id cannot be used to retrieve the variables in the first session file mentioned above, because this session id is not the "key" to open it ". If the code session_id ($ session id) is added before session_start (); no new session file is generated and the session file corresponding to this id is directly read.
2. Common Session functions and usage
2.1 Session_start (): Start a session or return an existing session.
This function has no parameters and returns true. If you use a cookie-based session, the browser cannot output any output before Session_start () is used. in php. start the session in ini. auto_start = 1, so you do not need to call session_start () every time before using the session (). However, enabling this option also has some restrictions. If the session is enabled. auto_start, the object cannot be put into the session, because the class definition must be loaded before the session is started to recreate the object in the session.
2.2 register SESSION variables:
PHP5 registers the SESSION global variable with $ _ SESSION ['xxx'] = xxx. Note session_register (),
Session_unregister and session_is_registered are no longer used in php5 unless you set
Register_globle is set to on, but it is strongly recommended to disable register_globle for security reasons.
HTTP_SESSION_VARS is not recommended. We recommend that you use $ _ SESSION instead.
Page1.php
<? Php
Session_start (); // This function must be called before SESSION is used.
$ _ SESSION ['name'] = "I am a black tornado Li Yun !"; // Register a SESSION variable
$ _ SESSION ['passwd'] = "mynameislikui ";
$ _ SESSION ['time'] = time ();
// If the client supports cookies, the session can be passed to the next page through this link.
Echo '<br/> <a href = "page2.php"> pass SESSION through COOKIE </a> ';
// When the client does not support cookies, use this method to pass sessions.
Echo '<br/> <a href = "page2.php? '. SID.' "> pass SESSION through URL </a> ';
Page2.php
<? Php
Session_start ();
Echo $ _ SESSION ['name'];
Echo $ _ SESSION ['passwd'];
Echo date ('y m d H: I: s', $ _ SESSION ['time']);
Echo '<br/> <a href = "page1.php"> back to the previous page </a> ';
?>
2.3 session_id ([string $ id]): Get and/or set the current session id
In php5, you can use session_id () or get the session_id and session_name of the current session by the SID appended to the url.
If session_id () has a specific value (that is, the $ id parameter is specified), the current session_id value will be replaced. Before using this function, you must start the session: session_start ();
Example: manually set the Session lifetime:
<? Php
Session_start ();
// Save for one day
$ LifeTime = 24*3600;
Setcookie (session_name (), session_id (), time () + $ lifeTime ,"/");
?>
In fact, the Session also provides a function session_set_cookie_params (); To set the Session lifetime. This function must be called before the session_start () function is called:
<? Php
// Save for one day
$ LifeTime = 24*3600;
Session_set_cookie_params ($ lifeTime );
Session_start ();
$ _ SESSION ["admin"] = true;
?>
If the client uses IE 6.0, session_set_cookie_params (); the function sets the Cookie. Therefore, we need to manually call the setcookie function to create the cookie.
2.4 check whether the session exists?
In previous php versions, session_is_register () is used to check whether a session exists. If you use $ _ SESSION ['xxx'] = XXX to register a session variable, session_is_register () function no longer works. You can use
Isset ($ _ SESSION ['xxx.
2.5 If the session_id session_regenerate_id ([bool $ delete_old_session]) is changed successfully, true is returned. If the session fails, false is returned.
This function can be used to change the session_id of the current session, but other information of the current session is not changed by default, unless $ delete_old_session is true. For example:
<? Php
Session_start ();
$ Old_sessionid = session_id ();
Session_regenerate_id ();
$ New_sessionid = session_id ();
Echo "original SessionID: $ old_sessionid <br/> ";
Echo "New SessionID: $ new_sessionid <br/> ";
Echo "<pre> ";
Print_r ($ _ SESSION );
Echo "</pre> ";
?>
2.6 session_name () returns the name of the current session or changes the name of the current session. To change the name of the current session, you must call this function before session_start. Note: session_name cannot be composed of only numbers. It must contain at least one letter. Otherwise, a new session id will be generated every moment.
Session renaming example:
<? Php
$ Previus_name = session_name ("WebsiteID ");
Echo "new session name: $ previus_name <br/> ";
?>
 
2.7 how 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.1 There are two ways to pass a session ID: cookie URL parameter
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 the constant SID. If the client does not send a session cookie, the SID format is session_name = session_id. Otherwise, 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 passed session variable var1 value is: www.2cto.com". $ _ SESSION ['var1'];
?>
 
Third approach:
Login.html
<! Doctype html public "-// 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. Solutions for 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 a question about how each server shares SESSION data.
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.2cto.com cannot read or write the cookies set by the server www.bbb.com. The servers of the same website have their own special characteristics, that is, they belong to the same level-1 domain. For example, both aaa.infor96.com and www.infor96.com belong to the domain .infor96.com, then we can set the COOKIE domain to .infor96.com, so that aaa.infor96.com and www.infor96.com can all 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.
For details about how to put sessions into a database, see php programming and the following webpage.
Http://www.eb163.com/article.php? Id = 75 & PHPSESSID = d226cc07cec0580ec7dad47119ee4667 from Crazy Coding life of Heda Lixin
 
 
 

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.