PHP sets the lifetime of the session

Source: Internet
Author: User
Tags empty garbage collection implement session id php session string variable valid

This article mainly shares the knowledge about the life cycle of the PHP session.

First of all, the beginning of the session creation to the end of the process.

When a program needs to create a session for a client's request, the server first checks to see if the client already contains a session identifier, which we call the session ID (Get the Method session_id ()), if it already contains a session The ID indicates that the client has previously created a session, and the server retrieves the value from the session by the session ID, and if the client does not include a session ID, which indicates that the client first requested the server or manually purged the cached file, create a Session and generates a session ID associated with this session, in general, the value of the session ID is not duplicated, and the encrypted string, which is returned to the client for saving in this response.

When is the session created?

Usually (usually) is created when the browser first requests it to the server, and it takes up a certain amount of memory, so when it is not necessary, the session is closed as much as possible.

When will the session be deleted?

Typically, sessions are deleted in these situations:

The first is to use the Session_destroy () reset function manual deletion;

The second is that the session's last active time distance from the current time is more than the timeout setting time; the third is that the server process is stopped.

How do I delete a session when the browser closes?

In theory, this is not the case, HTTP is a stateless protocol, so the server does not know when the client turned off the browser, and PHP does not have a customs function to get this information, but this problem can be solved, is to use the web effects code window.oncolose To monitor the browser's shutdown action, and then use Ajax to send a request to the server to delete the session, but this approach will not completely solve the problem, because in some cases, such as browser crashes, sudden power outages, the user panic and so these times do not respond.

How do I set the session to expire automatically after a period of time (delete)?

Session_Start () is the beginning of the session mechanism, it has a certain probability to open garbage collection, because the session is stored in the file, PHP itself garbage collection is invalid, the session of the recovery (delete) is to delete files, This probability is based on the configuration of php.ini, but some systems are session.gc_probability = 0, which means that the probability is 0, but the cron script is used to implement garbage collection (that is, delete session).

The default session duration in PHP is 1440 seconds (24 minutes, note: The default in the PHP5 is 180), that is, the client has not been refreshed for more than 24 minutes, and current sessions will be invalidated. Obviously, this is not enough to meet the needs.

One known way to work is to use Session_set_save_handler to take over all session management, typically storing session information in a database so that all expired sessions can be deleted through SQL statements. Control the duration of the session precisely. This is also a large web site based on PHP commonly used methods. However, the general small Web site, it seems not necessary so multi-point.

But the life of the general session is limited, if the user closed the browser, you can not save the variable session! So how can you achieve the permanent life of the session?

As you know, the session is stored on the server side, according to the SessionID provided by the client to get the user's file, and then read the file, get the value of the variable, SessionID can use the client's cookie or Http1.1 protocol Query_ String (that is, the "?" of the URL that is accessed) Later) to the server, and the server reads the directory of the session.

To achieve the permanent lifetime of the session, you first need to know about the php.ini settings (open php.ini file, in the [Session] section):

1, Session.use_cookies: The default value is "1", on behalf of SessionID use cookies to pass, the other is the use of query_string to pass;

2, Session.name: This is sessionid stored variable name, may be cookies, may also be query_string to pass, the default value is "PHPSESSID";

3, Session.cookie_lifetime: This represents SessionID in the client cookie storage time, the default is 0, on behalf of the browser a close sessionid on the void ... This is why the session cannot be used permanently!

4, Session.gc_maxlifetime: This is the session data stored on the server side of the time, if more than this time, then the session data will be automatically deleted!

There are a lot of settings, but this is related to this article is that, the following next how to use the principle of permanent session and procedures.

Previously said, the server through the SessionID to read the session data, but the General browser transfer SessionID in the browser after the shutdown is not, then we only need to artificially set SessionID and save, not on it. If you have the right to operate the server, setting this is very, very simple, just the following steps are required:

1, the "Session.use_cookies" set to 1, open the cookie store SessionID, but the default is 1, generally do not have to modify;

2, the "session.cookie_lifetime" Change to positive infinity (of course, there is no positive infinite parameters, but 999999999 and positive infinity is no difference);

3, the "Session.gc_maxlifetime" set to and "Session.cookie_lifetime" the same time;

In the PHP documentation, it is clear that the parameter that sets the session lifetime is session.gc_maxlifetime. You can modify this parameter either in the php.ini file or through the Ini_set () function. The problem is that after a lot of testing, modifying this parameter basically does not work, the session is still valid for 24 minutes of the default value.

Because of the working mechanism of PHP, it does not have a daemon thread that periodically scans the session information and determines whether it is invalidated. When a valid request occurs, PHP is based on the value of the global variable Session.gc_probability/session.gc_divisor (which can also be modified by the php.ini or Ini_set () function). To decide whether to start a GC (garbage Collector).

By default, session.gc_probability = 1,session.gc_divisor = 100, which means that there is a 1% probability that the GC will start. The work of the GC is to scan all session information, using the current time minus the last modification time of the session (modified date), compared to the session.gc_maxlifetime parameter, if the survival time has exceeded gc_ Maxlifetime, the session is deleted.

So far, everything is working fine. Then why is there a situation where gc_maxlifetime is invalid?

By default, session information is stored in the system's temporary file directory as a text file. Under Linux, this path is typically \tmp, and is typically C:\Windows\Temp under Windows. When there are multiple PHP applications on the server, they keep their session files in the same directory. Similarly, these PHP applications will start the GC at a certain rate, scanning all session files.

The problem is that GC does not differentiate between sessions of different sites when it is working. For example, site A's gc_maxlifetime is set to 2 hours, and Site B's gc_maxlifetime is set to the default 24 minutes. When the GC at Site B is started, it scans the public temporary files directory and deletes all session files that are more than 24 minutes away, regardless of whether they come from site A or B. In this way, the site A's gc_maxlifetime settings are in a fake.

Find out where the problem is, and it's easy to solve. Modify the Session.save_path parameter, or use the Session_save_path () function to point the directory where the session is saved to a dedicated directory, and the Gc_maxlifetime parameters work properly.

Strictly speaking, is this a bug in PHP?

Another problem is that gc_maxlifetime can only guarantee the shortest time of session survival, not be able to save in more than this time after the sessions information will be deleted immediately. Because the GC is started on a probability basis and may not be started for a long time, a large number of sessions will still be valid after gc_maxlifetime.

One way to solve this problem is to increase the probability of session.gc_probability/session.gc_divisor, and if you mention 100%, you will solve the problem completely, but obviously it will have a serious impact on performance. Another method is to determine the lifetime of the current session in your code, and if you exceed Gc_maxlifetime, empty the current session.

But if you do not have the right to operate the server, it is more cumbersome, you need to rewrite the SessionID through the PHP program to achieve permanent session data preservation. Check php.net's function manual, you can see the "session_id" function: If no parameters are set, then the current SessionID is returned, and if the parameter is set, the current SessionID is set to the given value.

As long as the use of permanent cookies plus the "session_id" function, you can achieve permanent session data saved!

But for convenience, we need to know the server settings "Session.name", but the general user does not have the right to view the server's php.ini settings, but PHP provides a very good function "phpinfo", use this to view almost all of the PHP information!

<?php
phpinfo ();

Open the editor, enter the code above, and then run the program in the browser to see the relevant information about PHP. One of the "session.name" parameters, this is the server we need "Session.name", is generally "PHPSESSID".

After you have noted the name of the SessionID, we will be able to implement a permanent session data store!

<?php
session_start ();
Ini_set (' Session.save_path ', '/tmp/');
6 head
ini_set (' Session.gc_maxlifetime ', 21600);
Save one day
$lifeTime = * 3600;
Setcookie (Session_name (), session_id (), time () + $lifeTime, "/");

In addition to setting the life time of PHP session, online to see a netizen wrote a very good method, here will share the code:

<?php
function start_session ($expire =0) {
	if ($expire ==0) {
		$expire =ini_get (' session.gc_ Maxlifetime ');
	} else{
		ini_set (' Session.gc_maxlifetime ', $expire);
	}
	if (Empty ($_cookie[' Phpsessid ')) {
		session_set_cookie_params ($expire);
		Session_Start ();
	} else{
		session_start ();
		Setcookie (' Phpsessid ', session_id (), time () + $expire);
	}

The use method is also simple, for example:

<?php start_session (600);//600 seconds after expiration

PostScript: In fact, the real permanent storage is not possible, because the cookie storage time is limited, and the server space is limited ... But for some need to save time longer site, the above method is enough!



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.