How to use the session in PHP _php tutorial

Source: Internet
Author: User
Tags session id setcookie

How to use the session in PHP

Declaration and use of the session

The session setting differs from the cookie, which must be started first and must be called session_start () in PHP. The syntax format for the session_start () function is as follows:

Bool session_start (void)//create session, start a conversation, perform session initialization

Note: the Session_Start () function cannot have any output before

When the site is first visited, the Seesion_start () function creates a unique session ID and automatically saves the session ID to the client cookie via the HTTP response header. At the same time, a file named after session ID is created on the server side to hold the user's conversation information. When the same user accesses the site again, the Seesion ID saved in the cookie is automatically sent over the HTTP request header, and the Session_Start () function will no longer allocate a new session ID. Instead, in the server's hard disk to find and the session ID of the session file, the previously saved for the user to read the conversation information, in the current script application, to track the purpose of this user. Session is used in the form of an array, such as $_session[' Session name ']

Register a session variable and read session

Using the session variable in PHP, in addition to starting, the process of registration. Registering and reading session variables is done by accessing the $_session array. The key names in the $_session associative array have the same naming conventions as normal variables in PHP. The code for registering the session variable is as follows:

The code is as follows

Initialization of the start session
Session_Start ();
Register session variable, assign a user's name
$_session["username"]= "Skygao";
Register session variable, assign a user's ID

After executing the script, the two session variables are saved in a file on the server side, the location of the file is through the php.ini file, under the directory specified by the Session.save_path property.

Unregister variables and destroy session

When you have finished using a session variable, you can delete it and destroy it when you have completed a conversation. If the user exits the web system, it is necessary to provide him with a logout function to destroy all of his information on the server. To destroy all the data related to the current session, you can call the Session_destroy () function to end the current session and empty all resources in the session. The syntax format for this function is as follows:

BOOL Session_destroy (void)//Destroy all information related to the current session

The function does not release the variables associated with the current session, nor does it delete the session stored in the client cookie

Id. Because the $_session array and the custom array are the same in use, we can use the unset () function to free up the individual variables registered in the session. As shown below:

unset ($_session[' key Name ']);

It is important to note that you do not use unset ($_session) to delete the entire $_session array, so you can no longer register variables with the $_session Hyper-global array. However, if you want to delete all the variables that a user registers in the session, you can assign the array variable $_session to an empty array directly. As shown below:

$_session=array ()

The default session of PHP is cookie-based, session

The ID is stored by the server in the client's cookie, so it is necessary to clear the SessionID stored in the cookie when unregistering the session, which must be done with the help of the Setcookie () function. In a PHP script, you can get the session name by calling the Session_name () function. Delete the session saved in the client cookie

ID, the code looks like this:

code as follows
!--? P HP
//Determine if there is a session ID
if (isset ($_cookie[session_name ())) {
//delete the cookie containing the session ID in the cookie, Note that the fourth parameter must be the same path as the php.ini set
Setcookie (Session_name (), ', Time () -3600, '/');

Through the previous introduction can be summed up, the session of the logoff process requires a total of 4 steps. In the following example, the complete four step code is provided, and the script can be run to close the session and destroy all resources related to this session. The code looks like this:

The code is as follows

First step: Open session and initialize
Session_Start ();

Part II: Delete all SESSION variables, or you can use Unset ($_session[xxx]) to delete them individually
$_session = Array ();

Part III: If you use a cookie-based session, use Setcookkie () to delete the cookie that contains the session ID
if (Isset ($_cookie[session_name ())) {
Setcookie (Session_name (), "", Time ()-42000, "/");

Fourth: Final and complete destruction of session
Session_destroy ();


Phpini configuration options for session

Several common configuration options for the php.ini file and session:

Session.auto_start = 0; Initializing session at request startup

Session.cache_expire = 180; Set the session document in the cache to obsolete after n minutes

Session.cookie_lifetime = 0; Sets the save time of the cookie in seconds, which is equivalent to setting the session expiration time, which is 0 until the browser is restarted

Session.auto_start=1, so that you do not need to call session_start () before each use of the session is not recommended. But there are some restrictions on enabling this option, if Session.auto_start is indeed enabled, You cannot put an object into a session because the class definition must be loaded before the session is started to rebuild the object in the session.

Session.cookie_path =/; Valid path for cookies

Session.cookie_domain =; The valid domain of the cookie = PHPSESSID; The name of the session used in the cookie.

Session.save_handler = files; control mode for saving/retrieving data

Session.save_path =/tmp; The parameters that are passed to the controller when the Save_handler is set to a file, which is the path to which the data file will be saved.

Session.use_cookies = 1; Whether to use cookies

Automatic garbage recovery mechanism of session

You can use the Session_destroy () function to provide an "exit" button in the page to destroy the session by clicking it. However, if the user does not click the Exit button, but directly close the browser, or off the network, etc., the session file saved on the server side will not be deleted. While closing the browser, the next time you need to reassign a new session ID to re-login, but this is only because of the settings in PHP.ini seesion.cookie_lifetime=0, to set the session ID in the client cookie valid period, Specifies the lifetime of the cookie sent to the browser, in seconds. The session ID disappears automatically when the session expires, regardless of whether the browser is turned on or not. While the client session ID disappears the server-side save session file is not deleted. Therefore, the server-side session file, which is not referenced by the Sessoin ID, becomes "garbage".

Server saved session file is a normal text file, so there will be file modification time. After the "garbage collection program" starts, it will delete all expired session files based on the time of the session file modification. Specify a time (in seconds) by setting the Session.gc_maxlifetime option in php.ini, such as setting the option value to 1440 (24 minutes). The garbage collector will be found in all session files and will be removed if the modification time is greater than 1440 seconds from the current system time.

What is the startup mechanism of the "Session garbage collection program"? The garbage collector is started when the session_start () function is called. A Web site has multiple scripts, no scripts to use the Session_Start () function to open the session, and there will be many users concurrently access, it is likely that the session_start () function is called n times in 1 seconds, and if each time the "Session garbage collection program will be started "That's very unreasonable. You can set the probability of starting a garbage collection program by modifying the "session.gc_probability and Session.gc_divisor" two options in the php.ini file. Calculates probabilities based on "session.gc_probability/session.gc_divisor", such as option Session.gc_probability=1, and option session.gc_divisor= 100, the probability is "1/100", that is, the session_start () function is called 100 times before it is possible to start the "garbage collection program."

Related configurations in php.ini

session.cookie_lifetime=0; Close browser The corresponding cookie file is deleted

Session.gc_maxlifetime; Set expiration session time, default 1440 seconds (24 minutes)

Session.gc_probability/session.gc_divisor; Probability of starting the garbage collection mechanism (recommended value is 1/1000--5000)

The ID of the session is passed through the URL when the cookie is banned

Using the session to track a user, is to pass a unique session ID between each page, and through the session ID to extract the user in the server saved session variables. The following two types of session ID transfer methods are common.

The first method is to pass the session ID in a cookie-based manner, which is better, but not always available, because the user can block Cokie on the client;

The second method is to pass the URL parameter and embed the session ID directly into the URL.

In the implementation of the session is usually the use of a cookie, the client saves the session ID is a cookie. When the customer disables the cookie, the session ID cannot be saved in the cookie, nor can it be passed between pages, at which time the session expires. However, the PHP5 can automatically check the cookie status on the Linux platform, and if the client disables it, the system automatically attaches the session ID to the URL for delivery. Using a Windows system as a Web server does not have this capability.

In PHP, another mechanism to track the session, if the customer browser does not support cookies, PHP can rewrite the URL of the customer request, the session ID added to the URL information. You can manually add a session ID to the URL of each hyperlink, but the workload is large, and this method is not recommended. As shown below:

The code is as follows

Open session
Session_Start ();

Append a parameter after each URL, the variable name Session_name () gets the name, and the value is obtained by session_id ()
Echo ' Connect demo ';
When using the Linux system as a server, when editing PHP, if you use the –ENABLE-TRANS-SID configuration option, and the runtime option Session.use_trans_sid are activated, when the client disables cookies, The relative URL is automatically modified to contain the session ID. If this is not configured, or if you are using a Windows system as a server, you can use a constant SID. The constant is defined when the session is started, and if the client does not send the appropriate session cookie, the SID is in the format session_name=session_id, or an empty string. Therefore, it can be unconditionally embedded into the URL. In the following example, two script programs are used to demonstrate the method of passing the session ID.

Session_Start ();

$_session["username"]= "admin";

echo "Session ID:". session_id (). "


Pass session ID via URL

In script test2.php, the output test1.php script saves another user name in the session variable. Again in this page to output a session ID, by comparison to determine whether two scripts use the same session ID. Also, when you turn cookies on or off, notice the changes in the URL in the browser's address bar. The code looks like this:

The code is as follows

Session_Start ();

echo $_session["username"]. " < br> ";
echo "Session ID:". session_id (). "
?> true techarticle How to use the session in PHP in detail the declaration of the session and the setting of the session is different from the cookie, which must be started first and must be called session_start () in PHP. Syntax of the session_start () function ...

  • 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.