Session declaration and use

Session Settings are different from cookies in that they must be started first, and in PHP you must call session_start(). The syntax for the session_start() function is as follows:

  Bool session_start(void) // Create a Session, start a Session, initialize the SessionNote: the session_start() function cannot have any output before itCopy the code

The Seesion_start() function creates a unique Session ID when visiting a site for the first time and automatically stores this Session ID in the client Cookie via the HTTP response header. At the same time, a file named Session ID is also created on the server to save the Session information of the user.

When the same user visits the site again, the Seesion ID stored in the Cookie is automatically carried over through the HTTP request header. Session_start() does not assign a new Session ID. Instead, find the Session file with the same name as the Session ID in the hard disk of the server, read out the Session information saved for the user before, and apply it in the current script to track the user. Session is used as an array, for example: $_SESSION[‘ Session name ‘]

Register a Session variable and read Session

To use the Session variable in PHP, you need to go through a registration process in addition to starting it. Session variables are registered and read by accessing the Session array. This is done in the _SESSION array. Done in 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 Session variables looks like this:


      
// Start session initialization
session_start();
// Register the session variable and assign it to a user name
$_SESSION["username"] ="skygao";
// Register the session variable and assign it to a user ID
$_SESSION["uid"] =1;
? >
Copy the code

After executing the script, the two Session variables are stored in a file on the server side in the directory specified by the session.save_path property in the php.ini file.

Unregister variables and destroy sessions

When a Session variable is used, it can be deleted, and when a Session is finished, it can be destroyed. If a user logs out of the Web system, he needs to be provided with a logout function, which destroys all his information in the server. Destroy all data related to the current Session by calling session_destroy() to terminate the current Session and clear all resources in the Session. The syntax for this function is as follows:

 bool session_destroy(void) // Destroy all data related to the current Session
Copy the code

This function does not release variables associated with the current Session, nor does it remove the SessionID stored in the client Cookie. Since the $_SESSION array is used identically to a custom array, we can use the unset() function to free individual variables registered in the Session. As follows:

 unset($_SESSION['keys']);
Copy the code

Do not use unset(SESSION) to delete the entire _SESSION array (unset(SESSION)) to delete the entire _SESSION array (unset(SESSION)). However, if you want to delete all the variables registered by a user in Session, you can directly register the array variable _SESSION as a global array variable. However, if you want to delete all the variables registered by a user in the Session, you can directly register the Session variable as a global array. However, if you want to delete all variables registered by a user in Session, you can simply assign the array variable _SESSION to an empty array. As follows:

 $_SESSION=array(a)Copy the code

PHP’s default Session is cookie-based. The SessionID is stored in the Cookie of the client by the server. Therefore, it is necessary to clear the SessionID stored in the Cookie when canceling the Session, which must be done by using the setCookie() function. In PHP scripts, you can get the Session name by calling the session_name() function. Delete the SessionID stored in the client Cookie as follows:


      
// Check whether the Cookie contains a session ID
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.'/');
}
? >
Copy the code

It can be concluded from the previous introduction that there are four steps in the Session logout process. In the following example, complete four-step code is provided, and running this script closes the Session and destroys all resources associated with the Session. The code looks like this:


      
// Step 1: Start the Session and initialize it
session_start();

$_SESSION[XXX] $_SESSION[XXX] $_SESSION[XXX
$_SESSION = array(a);// Step 3: If using a cookie-based session, use setCookkie() to delete the Cookie containing the session ID
if(isset($_COOKIE[session_name()])) {
    setCookie(session_name(), "", time()-42000."/");
}

// Step 4: Finally destroy the session
session_destroy();

? >
Copy the code

Phpini configuration option for session

The php.ini file has several common configuration options related to sessions:

session.auto_start = 0 ; Initialize the session when the request is started

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

session.cookie_lifetime = 0 ; Setting the cookie retention time by second is equivalent to setting the expiration time of the Session. A value of 0 indicates that the cookie is saved until the browser is restarted

Session.auto_start =1, so you don’t need to call session_start() every time you use a session. However, enabling this option has some limitations. If session.auto_start is indeed enabled, objects cannot be put into the session because the class definition must be loaded before the session is started to rebuild the object in the session.

session.cookie_path = / ; The valid path to cookie session.cookie_domain =; Valid field for cookie session.name = PHPSESSID; Save_handler = files; session.save_handler = files; Save_path = / TMP; session.save_path = / TMP; The parameter passed to the controller when save_handler is set to file, which is the path where the data file will be saved. Session.use_cookies =1; Whether to use cookiesCopy the code

Session automatic garbage collection mechanism

You can provide an exit button on the page with the session_destroy() function, which destroys the session by clicking on it. However, if the user does not click the exit button, but directly closes the browser, or disconnects from the network, the Session file saved on the server will not be deleted. While closing the browser,

The next time you need to reassign a new Session ID to log in again, but this is only because seesion. Cookie_lifetime =0 in php.ini sets the lifetime of the Session ID in the client Cookie. Specifies the lifetime of cookies sent to the browser in seconds. After the system grants a Session validity period, the Session ID automatically disappears regardless of whether the browser is enabled. The Session ID of the client disappears. The Session file saved on the server is not deleted. Therefore, server-side Session files that are not referenced by the Sessoin ID are “garbage”.

The Session file saved by the server is just a plain text file, so there is always a file modification time. After the garbage Collector is started, it deletes all expired Session files according to the modification time of Session files. Specify a time (in seconds) by setting the session.gc_maxLifetime option in php.ini, such as 1440(24 minutes). The Garbage Collector checks all Session files and deletes any changes that are more than 1440 seconds from the current system time.

How does the session garbage collector start up? The garbage collector is started when the session_start() function is called. Session_start () will be called N times in 1 second. If the session garbage collector is started each time, This is very unreasonable.

You can modify session.gc_probability and session.gc_divisor in the php.ini file to set the probability of starting the garbage collection program. The calculation probability is displayed based on session.gc_probability/session.gc_divisor. For example, session.gc_probability=1, session.gc_divisor=100, The probability is “1 in 100,” meaning that session_start() is called 100 times before the garbage collector is started.

php.iniRelated configuration in

session.cookie_lifetime=0; Session. gc_maxlifetime; Set the session expiration time. Default1440Seconds (24Minutes) session. Gc_probability/session. Gc_divisor; Probability of starting the garbage collection mechanism (recommended value is1/1000-5000)
Copy the code

When cookies are disabled, the SESSION ID is passed through the URL

Using Session to track a user is done by passing a unique Session ID between pages and extracting the Session variables that the user has saved on the server. There are two common methods for transferring Session ids.

The first method is to pass the session ID in cookie-based mode, which is better but not always available because the user can block the COkie on the client side.

The second method is to pass in the URL parameter, embedding the session ID directly into the URL.

Cookie is usually used in the implementation of Session, and the Session ID saved by the client is a Cookie. When the client disables cookies, the Session ID cannot be stored in the Cookie and cannot be passed between pages, and the Session expires. However, PHP5 can automatically check the Cookie status on Linux, and if the client disables it, the system will automatically attach the Session ID to the URL for transmission. This function is unavailable when the Windows system is used as the Web server.

Another mechanism for tracking sessions has been proposed in PHP. If cookies are not supported by the client’s browser, PHP can rewrite the URL requested by the client to add the Session ID to the URL information. You can manually add a Session ID to each hyperlink URL, but this method is not recommended because it requires a lot of work. As follows:


      
/ / open the session
session_start();

// Append parameters to each URL. The variable name is session_name() and the value is session_id()
echo '.session_name().'='.session_id().'> ';
? >When using Linux as a server, if the -- enabl-trans-sid configuration option is used when editing PHP, and the runtime option session.use_trans_SID is enabled, the relative URL is automatically changed to include the session ID when the client disables cookies. If this is not configured, or if you are using Windows as the server, you can use the constant SID. This constant is defined at session startup, and the SID is of the format session_name=session_id if the client does not send the appropriate session Cookie, otherwise an empty string. Therefore, it can be embedded in the URL unconditionally. In the following example, two scripts are used to demonstrate the Session ID passing method.
      
session_start();

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

echo "session ID:".session_id()."<br>";

? >
Copy the code

The above content hopes to help you, more free PHP factory PDF, PHP advanced architecture video materials, PHP wonderful good article can be wechat search concerns: PHP open source community

2021 Jinsanyin four big factory interview real questions collection, must see!

Four years of PHP technical articles collation collection – PHP framework

A collection of four years’ worth of PHP technical articles – Microservices Architecture

Distributed Architecture is a four-year collection of PHP technical articles

Four years of PHP technical essays – High Concurrency scenarios

Four years of elite PHP technical article collation collection – database