Php Session usage (very comprehensive)-PHP source code

Source: Internet
Author: User
Tags php session
This article covers session Declaration, session destruction, and session configuration and recovery mechanisms, as well as some common examples. I hope this article will help you. This article covers session Declaration, session destruction, and session configuration and recovery mechanisms, as well as some common examples. I hope this article will help you.

Script ec (2); script

Session Declaration and use

Session settings are different from cookies and must be started first. session_start () must be called in PHP (). The syntax format of the session_start () function is as follows:
Bool session_start (void) // creates a Session, starts a Session, and initializes the Session.
Note: No output is available before the session_start () function.
When you access the website for the first time, the Seesion_start () function creates a unique Session ID and automatically saves the Session ID to the client Cookie through the HTTP response header. At the same time, a file named after the Session ID is created on the server to save the Session information of this user. When the same user accesses this website again, the Seesion ID stored in the Cookie is automatically carried over the HTTP request header. In this case, Session_start () instead of allocating a new Session ID, the function searches for the Session file with the same name as the Session ID on the server's hard disk and reads the Session information previously saved for the user, apply it in the current script to track this user. The Session is used as an array, for example, $ _ SESSION ['session name']
Register a Session variable and read the Session
Using Session variables in PHP requires registration in addition to startup. To register and read Session variables, you must access the $ _ SESSION array. The key names in the $ _ SESSION join array have the same naming rules as common variables in PHP. The code for registering a Session variable is as follows:

The Code is as follows:

// Start session Initialization
Session_start ();
// Register the session variable and assign a value to the name of a user
$ _ SESSION ["username"] = "skygao ";
// Register the session variable and assign a value to the ID of a user
$ _ SESSION ["uid"] = 1;

After the script is executed, the two Session variables are saved in a file on the server. The file is located in the directory specified by the session. save_path attribute through the php. ini file.

Unregister variables and destroy sessions

After a Session variable is used, it can be deleted. After a Session is completed, it can also be destroyed. If you exit the Web system, you need to provide a logout function for the user to destroy all his information on the server. To destroy all information related to the current Session, you can call the session_destroy () function to end the current Session and clear all resources in the Session. The syntax format of this function is as follows:
Bool session_destroy (void) // destroy all information related to the current Session
This function does not release the variables related to the current Session, nor delete the Session stored in the client Cookie.
ID. Because the $ _ SESSION array is the same as the custom array, we can use the unset () function to release a single variable registered in the Session. As follows:
Unset ($ _ SESSION ['key name']);
Be sure not to use unset ($ _ SESSION) to delete the entire $ _ SESSION array. In this way, variables cannot be registered through the $ _ SESSION over the global array. However, if you want to delete all the variables registered by a user in the Session, you can directly assign the array variable $ _ SESSION to an empty array. As follows:
$ _ SESSION = array ()
The default Session of PHP is Cookie-based.
The ID is stored by the server in the Cookie of the client. Therefore, you must clear the SessionID stored in the Cookie when canceling the Session, which must be completed by using the setCookie () function. In a PHP script, you can call the session_name () function to obtain the Session name. Delete the Session stored in the client Cookie
The Code is as follows:

The Code is as follows:
// Determine whether the session ID exists in the Cookie
If (isset ($ _ COOKIE [session_name ()]) {
// Delete the cookie containing the Session ID. Note that the fourth parameter must be the same as the path set in php. ini.
Setcookie (session_name (), '', time ()-3600 ,'/');

According to the previous introduction, it can be concluded that the cancellation process of the Session requires four steps. In the following example, you can run the full four-step code to close the Session and destroy all resources related to the Session. The Code is as follows:

The Code is as follows:

// Step 1: Enable Session and initialize
Session_start ();

// Part 2: delete all Session variables. You can also use unset ($ _ SESSION [XXX]) to delete them one by one.
$ _ SESSION = array ();

// Part 3: If a Cookie-based session is used, use setCookkie () to delete the cookie containing the Session ID.
If (isset ($ _ COOKIE [session_name ()]) {
SetCookie (session_name (), "", time ()-42000 ,"/");

// Part 4: completely destroy the session
Session_destroy ();


Phpini configuration options of the session

Several common configuration options related to the php. ini file and Session:
Session. auto_start = 0; initialize the session when the request starts.
Session. cache_expire = 180; set the cached session document to expire after n minutes
Session. cookie_lifetime = 0; set the cookie retention time in seconds, which is equivalent to setting the Session expiration time. If it is set to 0, it indicates that the browser is restarted.
Session. 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.
Session. cookie_path =/; valid cookie Path
Session. cookie_domain =; valid domain of the cookie
Session. name = PHPSESSID; name of the session used in the cookie
Session. save_handler = files; Control Method for saving/retrieving data
Session. save_path =/tmp; the parameter passed to the controller when save_handler is set to a file, which is the path to save the data file.
Session. use_cookies = 1; whether to use cookies

Automatic garbage collection mechanism of Session

You can use the session_destroy () function to provide an "exit" button on the page and click destroy session. However, if the user does not click the exit button, but directly closes the browser or breaks the network, the Session files saved on the server will not be deleted. Although the browser is closed, you need to re-allocate a new Session ID to log on again next time, but this is only because. set seesion in ini. cookie_lifetime = 0 to set the validity period of the Session ID in the client Cookie. the life cycle of the Cookie sent to the browser is specified in seconds. After the system gives the Session validity period, the Session ID automatically disappears regardless of whether the browser is enabled or not. The client Session ID disappears and the Session file saved by the server is not deleted. Therefore, the server Session file that is not referenced by Sessoin ID becomes "junk ".
The Session file stored on the server is a common text file, so there will be a file modification time. After the garbage collection program is started, all expired Session files are deleted based on the modification time of the Session file. Set the session. gc_maxlifetime option in php. ini to specify a time (unit: seconds). For example, set this option to 1440 (24 minutes ). The "garbage collection program" will be checked in all Session files. If there is a modification time greater than 1440 seconds from the current system time, it will be deleted.
What is the startup mechanism of the "session garbage collection program? The garbage collection program is started when the session_start () function is called. A website has multiple scripts. If there are no scripts, you must use the session_start () function to enable the session, and many users access the session simultaneously. This is likely because session_start () the function is called N times in one second. If the "session garbage collection program" is started every time, this is unreasonable. You can modify the "session. gc_probability and session. gc_pisor" options in the php. ini file to set the probability of starting the garbage collection program. According to the "session. gc_probability/session. gc_pisor "calculates the probability of publicity, for example, the option session. gc_probability = 1, and option session. gc_pisor = 100. The probability is "1/100", that is, the session_start () function is called 100 times before it can start the "garbage collection program ".

Related configurations in php. ini
Session. cookie_lifetime = 0; close the browser and delete the corresponding cookie file.
Session. gc_maxlifetime; set the expiration time of the session. The default value is 1440 seconds (24 minutes)
Session. gc_probability/session. gc_pisor; probability of starting the garbage collection mechanism (Recommended Value: 1/1000 -- 5000)

The session ID is passed through the URL when the cookie is disabled.

A Session is used to track a user by passing a unique Session ID between pages and extracting the Session variable that the user saves on the server through the Session ID. Common Session ID transfer methods are as follows.
The first method is to pass the session ID based on cookies. This method is better, but not always available, because the user can block cokie on the client;
The second method is to pass through the url parameter and directly embed the session ID into the URL.
In Session implementation, the Cookie is usually used. The Session ID stored by the client is a Cookie. When a customer disables a Cookie, the Session ID cannot be saved in the Cookie, and cannot be transferred between pages. In this case, the Session becomes invalid. However, on the Linux platform, PHP5 can automatically check the Cookie status. If the client disables it, the system automatically attaches the Session ID to the URL for transmission. Windows is not used as a Web server.
Another mechanism for tracking Session is proposed in PHP. If the client browser does not support cookies, PHP can rewrite the client request URL and add the Session ID to the URL Information. You can manually add a Session ID to the URL of each hyperlink, but the workload is large. We do not recommend this method. As follows:

The Code is as follows:

// Enable session
Session_start ();

// Append the parameter to each URL. The variable name is session_name () and the value is obtained through session_id ().
Echo 'Connection demo ';
When using the Linux system as the server, if the-enable-trans-sid configuration option is used during PHP editing, and when running the session option. use_trans_sid is activated. When Cookie is disabled on the client, the relative URL is automatically changed to include session ID. If this configuration is not configured, Or you use Windows as the server, you can use the constant SID. This constant is defined at session startup. If the client does not send an appropriate session Cookie, the SID format is session_name = session_id; otherwise, it is an empty string. Therefore, it can be embedded in the URL unconditionally. In the following example, two script programs are used to demonstrate the transfer method of the Session ID.

Session_start ();

$ _ SESSION ["username"] = "admin ";

Echo "session ID:". session_id ()."


"> Pass Session ID through URL
In the script test2.php, output another user name that the test1.php script saves in the Session variable. Output A Session ID on the page, and compare and determine whether the two scripts use the same Session ID. In addition, when enabling or disabling cookies, pay attention to the URL changes in the browser address bar. The Code is as follows:

The Code is as follows:

Session_start ();

Echo $ _ SESSION ["username"]. "<br> ";
Echo "session ID:". session_id ()."

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.