Follow me to learn PHP5: application and analysis of session

Source: Internet
Author: User
The Chinese translation of a Session is called "Session". its original meaning refers to a series of actions/messages starting and ending, for example, a series of processes from picking up a phone call and dialing to hanging up a phone call can be called a session. At present, the society is very confused about session: sometimes we can see that "the Chinese translation of Session during a browser session is called" Session ", the original meaning refers to a series of actions/messages that start and end, for example, a session can be called from the process of picking up the phone and dialing the phone to hanging up the phone. At present, the society is very confused about session: sometimes we can see this: "During a browser session ,... ", the session here refers to the period from opening a browser window to closing it. you can also see the sentence" the user (client) is in a session, it may refer to a series of actions of a user (generally a series of actions related to a specific target, such as the online shopping process from login to purchasing goods to checkout and logout; however, sometimes it may only refer to a connection. The difference can only be inferred from high and low texts.

However, when a session is associated with a network protocol, it often implies two meanings: "connection-oriented" and "/" persistence, "Connection orientation" refers to the establishment of a communication channel before the communication parties establish a communication channel, such as a call, until the other party receives a telephone communication before starting. "Persistence" means that the communication party can associate a series of messages so that messages can be mutually attached, for example, a waiter can recognize an old customer who has visited the store again and remembers that the customer still owes a dollar to the store. Such examples include "one TCP session" or "one POP3 session ".

Since such chaos cannot be changed, it is difficult to have the same scale for the next definition of the session. When browsing session-related materials, we can only infer from high and low texts. However, we can understand this: for example, when we make a call, we call the call from the moment we call the call to the end of the call, because the call is always in the connected state, so we call the session status. It is a public variable that persists during the interaction between visitors and all websites. when the client does not support cookies, SESSION variables are used to ensure data accuracy and security. Visitors to the website will be assigned a unique identifier, the so-called session ID. It is either stored in the client's cookie or transmitted through the URL.

The invention of SESSION makes up for the limitations of the HTTP protocol: the HTTP protocol is considered as a stateless protocol and cannot be known about the user's browsing status. after the server completes the response, the server lost contact with the browser. This is consistent with the original goal of the HTTP protocol. the client simply needs to request the server to download some files, and neither the client nor the server needs to record the previous actions of each other, each request is independent. for example, the relationship between a customer and an active vending machine or an ordinary (non-member) hypermarket is the same.

Therefore, SESSION (cookie is another solution) is used to record the user's information, so that the user can confirm the request to the web server again in this identity. The invention of session allows a user to retain his/her information when switching between multiple pages. Website programmers have such understanding that the variables on each page cannot be applied on the next page (although form and url can also be implemented, but this is a very unimagined measure ), the variables registered in the SESSION can be applied as global variables.

So what is the usefulness of SESSION? Shopping cart is used for online shopping. you can add your purchased items to the shopping cart at any time and check out the items at the cashier. In the whole process, the shopping cart has always played the role of temporary storage of the selected item, and used it to track users' movements on the website. this is the role of SESSION, which can be used for user identity authentication, program Status record, parameter transfer between pages, etc.

The COOKIE technique is used in SESSION implementation. The SESSION retains a COOKIE containing session_id (SESSION number) on the client, and other session variables, such as session_name, on the server side. When the user requests the server, the session_id is also sent together to the server. the session_id is used to extract the real variable stored on the server to identify who the user is. At the same time, it is not difficult to understand why the SESSION sometimes fails.

When the client disables cookies (click "tools"-"Internet options" in IE, and click "security"-"custom level" in the pop-up dialog box, set "promise COOKIE for each conversation" to disabled), session_id cannot be passed, and the SESSION becomes invalid. However, on the linux/unix platform, php5 can actively check the cookie status. if the client is disabled, the system automatically attaches the session_id to the url for transmission. Windows host does not have this function.

Common Session functions and usage?

Session_start (): start a session or return an existing session.

Note: This function has no parameters and returns true. If you apply cookie-based session, the browser cannot output any output before the application Session_start (). Otherwise, the following error occurs:

Warning: Cannot send session cache limiter-headers already sent (output started at/usr/local/apache/htdocs/cga/member/1.php: 2 )............

You can start session. auto_start = 1 in php. ini, so you do not need to call session_start () before each session application (). However, there are some restrictions on enabling this option. 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.

All registered variables will be serialized after the request ends. Registered but undefined variables are marked as undefined. In subsequent visits, these variables are not defined by the session module unless you define them later.

Warning some types of data cannot be serialized and therefore cannot be stored in sessions. Contains resource variables or objects with circular references (that is, an object passes a reference pointing to itself to another object ).

Register SESSION variables:

PHP5 application $ _ SESSION ['***'] = *** registers the SESSION global variable. It is similar to the application method of GET, POST, and COOKIE.

Note: session_register (), session_unregister, and session_is_registered are no longer used in php5 unless register_globle is set to on in php. ini. However, it is strongly recommended to disable register_globle for security reasons. HTTP_SESSION_VARS does not advocate applications. we recommend that you use $ _ SESSION instead. For example:


<? Php
Session_start (); // This function must be called before the SESSION is applied.
$ _ SESSION ['name'] = "I am a black tornado Li Yun !"; // Register a SESSION variable
$ _ SESSION ['passwd'] = "mynameislikui ";
$ _ SESSION ['Time'] = time ();
Echo '<br/> <a href = 'page2. php '> pass SESSION through COOKIE </a>'; // if the client supports cookie, the session can be passed to the next page through this link.
Echo '<br/> <a href = 'page2. php? '. SID. ''> pass SESSION through URL </a>'; // when the client does not support cookie, this measure is applied to pass session.

<? 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 Mountain 1 page </a> ';
There are two ways to pass a Session ID:

URL parameters

The session module supports these two methods. Cookie is more optimized, but because it is not always available, it also provides exchange methods. The second method directly inserts the session ID into the URL center.
PHP can transparently convert the connection. Unless it is an application of PHP 4.2 or an updated version, it must be manually activated during PHP compilation. In Unix, use -- enable-trans-sid to configure options. If this configuration option and the runtime option session. use_trans_sid are both activated (php. ini modified), the URI will be automatically corrected to include the session ID.

● Session_id

Session_id () is used to set or obtain the current session_id. In php5, you can apply session_id () or obtain the session_id and session_name of the current session by the SID appended to the url.

If session_id () has a specific value, it will replace the current session_id value. Before applying this function, you must start the session: session_start ();
When session cookies are applied, if a session_id () value is specified, each time session_start () is started, a cookie value will be sent to the client. Whether or not the current session_id is equal to the specified value.

If no value is specified for session_id (), the current session_id () is returned. if the current session is not started, an empty string is returned.

● Check whether the session exists?

In previous php versions, session_is_register () is usually 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 ['***']) to change it.

● If session_id session_regenerate_id () is changed successfully, true is returned. if it fails, false is returned.

You can use this function to change the session_id of the current session, but not the other information of the current session. 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> ';
● 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/> ';
● How to delete a session?

1. unset ($ _ SESSION ['***']) deletes a single session, unset ($ _ SESSION ['***']) used to unregister a registered session variable. Its role is the same as session_unregister. Session_unregister () is no longer used in PHP5 and can be entered into the cold Palace.

Unset ($ _ SESSION): This function cannot be applied. it will burn the global variable $ _ SESSION, and no feasible measures have been taken 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 or delete the client's session cookie. the default session of PHP is cookie-based. to delete a cookie, you must use the setcookie () function.

Return value: Boolean value.

Function Clarification: This function ends the current session. this function has no parameters and returns true.

Session_unset () if $ _ SESSION is applied, the function no longer works. Since PHP5 must be applied to $ _ SESSION, this function can be used in the cold room.

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 [***]) one by one. ****/
$ _ SESSION = array ();
/*** Delete sessin id. because the session is based on cookies by default, the setcookie is used to delete the cookie containing the session id .***/
If (isset ($ _ COOKIE [session_name ()]) {
Setcookie (session_name (), '', time ()-42000 ,'/');
// Finally, the session is permanently burned down.
Session_destroy ();
The procedure for deleting a Session is as follows:

① Session_start ()

② $ _ SESSION = array ()/unset ($ _ SESSION ['***'])

③ Session_destroy ()

● SESSION security:

The session module cannot guarantee that the information stored in the session can only be viewed by the user who created the session. Based on the data it stores, more measures are needed to actively protect the session integrity.

Evaluating the data carried in a session and implementing additional protection measures usually costs the user's convenience. For example, if you want to protect users from simple social policy violations (note: the session ID displayed in the URL will be seen by others on the computer screen, or by another website through HTTP Referer), the session should be enabled. use_only_cookies. In this case, the client must enable cookie unconditionally, otherwise the session will not work.

There are several ways to leak existing session IDs to third parties. The leaked session ID allows a third party to visit all resources associated with the specified ID. First, the URL carries the session ID. If you connect to an external site, a URL containing a session ID may be stored in the Referer log of the external site. Second, more active attackers may listen on packets in the network segment. If it is not encrypted, the session ID will flow over the network in plaintext. The solution is to implement SSL on the server and force the user to apply it.

By default, all data related to a specific session is stored in a file in the directory specified by session. save_path in The INI option. A file is created for each session (whether or not data is related to the session ). This is because every time a session is opened, a file is created, whether or not data is written into the file. Note that due to restrictions on working with the file system, this action has a side effect, which may result in the loss of sessions with custom session processors (such as databases) that do not store data.
The above content functions will be used below, but there are also some session-related functions:


Function functions: sesssion information encoding

Function prototype: string session_encode (void );

Return value: string

Function clarification: the returned string contains the name and value of each variable in the global variable, such as: a | s: 12: 'It is a test \ '; c | s: 4: 'Lala '; a is the variable name s: 12 represents the value of variable a. The length of it is a test is 12 variables separated by semicolons.


Function: decodes sesssion information.

Function prototype: boolean session_decode (string data)

Return value: Boolean

Function Clarification: This function decodes session information and returns the logical value true if the session information is successful.

Php5 no longer applies session_id, but changes it into a constant SID and keeps it in the cookie. If the cookie is disabled on the client, php will take the initiative to pass the SID through the url, the condition is to set session. use_trans_sid = 1 in php. ini. In this case, it does not matter even if the client disables the cookie.

Use strip_tags () to output SID to avoid XSS related attacks.

Session cross-page transfer Title:

Session cross-page transmission requires three considerations:

① Cookie is disabled on the client.

② The browser displays the title, 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.

Why? The following describes the cause:

The Session file is divided into two parts: the session variable is retained on the server side (the session is stored as a file by default), and the session id is retained on the client as a cookie. (Note: The session is cookie-based by default ).

When your browser requests the server, it also sends a cookie containing the session id (by default ). The server obtains the user's file based on the session id provided by the client, that is, the session variable value is retained on the server. In fact, the session id can apply the client's real Cookie or Query_String of the Http1.1 protocol (that is, the "?" 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 the session variables to be stored in the generated session file. The session id can be used to retrieve the defined variables. After a cross-page session, you must execute session_start () again to apply the session. a session file will be generated and the corresponding session id will be 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.

By default, session IDs are retained by the client's Cookie. Therefore, session IDs are affected when the client's cookie displays the title. It is important to note that the session does not necessarily need to be attached to the cookie, which is also superior to the cookie. When the client's Cookie is disabled or the title is displayed, PHP will automatically attach the session id to the URL, so that the session variable can be applied across pages through the session id. However, such attachment is also conditional. first, "php. session in ini. use_trans_sid = 1 or the -- enable-trans-sid option is enabled during compilation. Second, the server running PHP must be a unix/linux System. windows does not have this function.

After understanding the above principles, we can come up with three ways to solve the problem of transferring titles across pages of sessions:

1. set session. use_trans_sid = 1 in php. ini or enable the -- enable-trans-sid option during compilation, so that PHP can actively pass the session id across pages.

2. manually pass session IDs through URL values and hidden forms.

3. retain 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:


<? Php
Session_start ();
$ _ SESSION ['var1'] = 'People's Republic of China ';
$ Url = '<a href ='. '\ 's2. php \'> Next page </a> ';
Echo $ url;

<? 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, the result "the People's Republic of China" should be obtained ".

Now, if you manually close the client's cookie and run it again, you may not be able to get the result. If no result is obtained, "set session. use_trans_sid = 1 in php. ini or enable the -- enable-trans-sid option when compiling", and obtain the result "the People's Republic of China"

The second road:


<? Php
Session_start ();
$ _ SESSION ['var1'] = 'People's Republic of China ';
$ Sn = session_id ();
$ Url = '<a href ='. '\ 's2. php? S = '. $ sn. '\'> Next page </a> '; // PHP5 defines a constant SID to represent session_id (), $ url can also be written as $ url = '<a href = 'page2. php? '. SID. ''> Next page </a> ';
Echo $ url;

<? Php
Session_id ($ _ GET ['s ']);
Session_start ();
Echo 'the value of the passed session variable var1' is: '. $ _ SESSION ['var1'];
Third path:

<! Doctype html public '-// W3C // dtd html 4.01 Transitional // EN'>
<Title> Login </title>
<Meta http-equiv = 'content-type' Content = 'text/html; charset = ?????? '>
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'>

<? Php
$ Name = $ _ POST ['name'];
$ Pass = $ _ POST ['pass'];

If (! $ Name |! $ Pass ){
Echo 'user name or password is empty. Please <a href = \ 'login.html \ '> log on again </a> ';
Die ();
If (! ($ Name = 'laogong' & $ pass = '000000 ')){
Echo 'user name or password is incorrect. Please <a href = \ 'login.html \ '> log on again </a> ';
Die ();
// Register a user
Ob_start ();
Session_start ();
$ _ SESSION ['user'] = $ name;
$ Psid = session_id ();
$ Fp = fopen ('E: \ tmp \ phpsid.txt ', 'w ');
Fwrite ($ fp, $ psid );
Fclose ($ fp );
// The identity is successfully verified for coherent control
Echo 'logged on <br> ';
Echo '<a href = \ 'mylogin2. php \'> Next page </a> ';

<? 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 {
// Successful logon for coherent control
Echo 'Not logged on, not permitted to visit ';
Echo 'a href = \ 'login.html \ '> log on </a> and browse ';
Die ();

Related Article

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.