The default session validity period in PHP is 1440 seconds (24 minutes) [weiweiok Note: The default in PHP5 is 180 minutes], that is to say, if the client does not refresh for more than 24 minutes, the current session will expire. Obviously, this is not enough.
A known effective method is to use session_set_save_handler
to take over all session management work. Generally, the session information is stored in the database, so that all expired sessions can be deleted through SQL statements, accurately. Control the validity period of session. This is also a commonly used method for large websites based on PHP. However, for ordinary small websites, it seems that there is no need to work so hard.
But the general Session has a limited lifespan. If the user closes the browser, the Session variables cannot be saved! So how can we achieve the permanent life span of Session?
As we all know, the Session is stored on the server side. The user's file is obtained based on the SessionID provided by the client, and then Read the file to obtain the value of the variable. The SessionID can use the client's Cookie or Http1. 1 protocol's Query_String (that is, the part after the "?" of the accessed URL) is transmitted to the server, and then the server reads the Session directory...
To realize the permanent life of the Session, you first need to understand php .ini settings related to Session (open the php.ini file, in the "[Session]" section):
1. session.use_cookies: The default value is "1", which means that SessionID is passed by Cookie. Otherwise, use Query_String to pass;
2. session.name: This is the variable name stored in SessionID. It may be Cookie or Query_String to pass. The default value is "PHPSESSID";
3. session.cookie_lifetime : This represents the time the SessionID is stored in the client cookie. The default is 0, which means that the SessionID will be invalidated as soon as the browser closes... It is because of this that the Session cannot be used permanently!
4. session.gc_maxlifetime: This is the time that Session data is stored on the server side. If this time is exceeded, the Session data will be automatically deleted!
There are many more settings, but these are the ones related to this article. Let’s start with the principles and steps of using permanent Session.
As mentioned before, the server reads Session data through SessionID, but generally the SessionID sent by the browser is gone after the browser is closed, so we only need to manually set the SessionID and save it, isn't it...
If you have the operating permissions of the server, then setting this is very, very simple. You just need to perform the following steps:
1. Set "session.use_cookies" to 1 and turn on Cookie storage. SessionID, but the default is 1, generally does not need to be modified;
2. Change "session.cookie_lifetime" to positive infinity (of course there is no parameter for positive infinity, but there is no difference between 999999999 and positive infinity);
3. "session.gc_maxlifetime" is set to the same time as "session.cookie_lifetime";
It is clearly stated in the PHP documentation that the parameter for setting the session validity period is session.gc_maxlifetime. This parameter can be modified in the php.ini file or through the ini_set() function. The problem is that after many tests, modifying this parameter basically has no effect, and the session validity period still maintains the default value of 24 minutes.
Due to the working mechanism of PHP, it does not have a daemon thread to scan session information regularly and determine whether it is invalid. When a valid request occurs, PHP will decide whether to start a GC (Garbage Collector) based on the value of the global variable session.gc_probability/session.gc_pisor (which can also be modified through the php.ini or ini_set() function). By default, session.gc_probability = 1, session.gc_pisor = 100, which means there is a 1% probability that GC will be started. GC
's job is to scan all session information, subtract the last modification time (modified date) of the session from the current time, and compare it with the session.gc_maxlifetime parameter. If the survival time has exceeded gc_maxlifetime, Just delete the session.
So far, everything is working normally. So why does gc_maxlifetime become invalid?
By default, session information will be saved in the system's temporary file directory in the form of text files. Under Linux, this path is usually \tmp, and under Windows it is usually C:\Windows\Temp
. When there are multiple PHP applications on the server, they will save their session files in the same directory. Similarly, these PHP applications will also start GC at a certain probability and scan all session files.
The problem is that when GC is working, it does not distinguish between sessions on different sites. 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 of site B starts, it will scan the public temporary file directory and delete all session files older than 24 minutes, regardless of whether they come from site A or B. In this way, the gc_maxlifetime
setting of site A is useless.
It’s easy to find the problem and solve it. 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. The gc_maxlifetime
parameter works normally.
Strictly speaking, is this a bug in PHP?
Another problem is that gc_maxlifetime can only guarantee the shortest time for the session to survive, and cannot be saved. After this time, the session information will be deleted immediately. Because GC is started based on probability and may not be started for a long period of time, a large number of sessions will still be valid after exceeding gc_maxlifetime. One way to solve this problem is to increase the probability of session.gc_probability/session.gc_pisor. If mentioned to 100%, this problem will be completely solved, but it will obviously have a serious impact on performance. Another method is to determine the lifetime of the current session in your code. If it exceeds gc_maxlifetime, clear the current session.
But if you do not have the operating authority of the server, it will be more troublesome. You need to rewrite the SessionID through the PHP program to achieve permanent session data storage. Check the function manual of php.net and you can see the "session_id" function: if no parameters are set, the current SessionID will be returned. If the parameters are set, the current SessionID will be set to the given value...
As long as you use a permanent Cookie and add the "session_id" function, you can save permanent Session data!
But for convenience, we need to know the "session.name" set by the server, but generally users do not have permission to view the php.ini settings of the server. However, PHP provides a very good function "phpinfo", which can be viewed using this Almost all PHP information!
-------------------------------------------------- -------------------------------------
-------------------------------- -------------------------------------------------- --
Open the editor, enter the above code, and then run the program in the browser, you will see PHP related information (as shown in Figure 1). There is a "session.name" parameter, which is the server "session.name" we need, usually "PHPSESSID".
After writing down the name of SessionID, we can achieve permanent Session data storage!
The code is as follows:
session_start(); ini_set('session.save_path','/tmp/'); //6个钟头 ini_set('session.gc_maxlifetime',21600); //保存一天 $lifeTime = 24 * 3600; setcookie(session_name(), session_id(), time() + $lifeTime, "/");
Postscript:
In fact, true permanent storage is impossible because the cookie storage time is limited and the server space is also limited...but For some sites that need to be saved for a long time, the above method is enough!
Put the session into mysql Example:
Create a table in the database: session (sesskey varchar32, expiry int11, value longtext)
code:
Connected to the database before executing the code .
The code is as follows:
define('STORE_SESSIONS','mysql'); if (STORE_SESSIONS == 'mysql') { if (!$SESS_LIFE = get_cfg_var('session.gc_maxlifetime')) { $SESS_LIFE = 1440; } function _sess_open($save_path, $session_name) { // 如果没有连接数据库,可以在此执行mysql_pconnect,mysql_select_db return true; } function _sess_close() { return true; } function _sess_read($key) { $value_query = mysql_query("select value from sessions where sesskey = '" .addslashes($key) . "' and expiry > '" . time() . "'"); $value = mysql_fetch_array($value_query); if (isset($value['value'])) { return $value['value']; } return false; } function _sess_write($key, $val) { global $SESS_LIFE; $expiry = time() + $SESS_LIFE; $value = $val; $check_query = mysql_query("select count(*) as total from sessions where sesskey = '" . addslashes($key) . "'"); $check = mysql_fetch_array($check_query); if ($check['total'] > 0) { return mysql_query("update sessions set expiry = '" . addslashes($expiry) . "', value = '" . addslashes($value) . "' where sesskey = '" . addslashes($key) . "'"); } else { return mysql_query("insert into sessions values ('" . addslashes($key) . "', '" . addslashes($expiry) . "', '" . addslashes($value) . "')"); } } function _sess_destroy($key) { return mysql_query("delete from sessions where sesskey = '" . addslashes($key) . "'"); } function _sess_gc($maxlifetime) { mysql_query("delete from sessions where expiry < '" . time() . "'"); return true; } session_set_save_handler('_sess_open', '_sess_close', '_sess_read', '_sess_write', '_sess_destroy', '_sess_gc'); } danoo_session_name( 'dtvSid' ); danoo_session_save_path(SESSION_WRITE_DIRECTORY);
I still don’t understand where the open and write parameters come from. Two commonly used functions to modify php.ini configuration: get_cfg_var('session.gc_maxlifetime'): Get the value of session.gc_maxlifetime ini_set('session.cookie_lifetime','0'): Set the value of session.cookie_lifetime to 0.
Related topic recommendations: php session (including pictures, texts, videos, cases)
The above is the detailed content of PHP session validity period problem. For more information, please follow other related articles on the PHP Chinese website!

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function