Home  >  Article  >  Backend Development  >  PHP session validity session.gc_maxlifetime_PHP tutorial

PHP session validity session.gc_maxlifetime_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:30:511048browse

A known and 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 and the validity period of the session can be accurately controlled. 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 the file is read to obtain the value of the variable. The SessionID can use the client's Cookie or the Query_String of the Http1.1 protocol (that is, (the part after the "?" in the accessed URL) is transmitted to the server, and then the server reads the directory of the Session...
To realize the permanent life of the Session, you first need to understand the relevant settings of the Session in php.ini (open php.ini file, in the "[Session]" section):
1. session.use_cookies: The default value is "1", which means that the SessionID is passed by Cookie, otherwise it is passed by Query_String;
2. session.name: This is the variable name stored in SessionID. It may be passed by Cookie or Query_String. The default value is "PHPSESSID";
3. session.cookie_lifetime: This represents the time that 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... 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, no...
If you have the permission to operate the server, 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 to store SessionID, but the default is 1. , generally no need to modify;
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. Set "session.gc_maxlifetime" It is 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 regularly scan session information 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_divisor (which can also be modified through the php.ini or ini_set() function).
By default, session.gc_probability = 1, session.gc_divisor = 100, which means there is a 1% probability that GC will be started. The job of the GC 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, the session will be deleted.
So far, everything is working fine. 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:WindowsTemp. 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 site B's GC 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.
Once you find the problem, it’s easy to 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_divisor. 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 permission to operate 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 most 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 used to view Almost all PHP information!
-------------------------------------------------- -------------------------------------
PHP related information display< /title> <br><?phpinfo()?> <br>-------------------------------- -------------------------------------------------- -- <br>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". <br>After writing down the name of the SessionID, we can achieve permanent session data storage! <br>The code is as follows: <br></p> <div class="codetitle"> <span style="CURSOR: pointer" onclick="doCopy('code63547')"><u>Copy code</u></span> The code is as follows:</div> <div class="codebody" id="code63547"> <br>session_start(); <br>ini_set('session. save_path','/tmp/'); <br>//6 hours<br>ini_set('session.gc_maxlifetime',21600); <br>//Save for one day<br>$lifeTime = 24 * 3600; <br>setcookie(session_name(), session_id(), time() + $lifeTime, "/"); <br> </div> <br>Postscript: <br>In fact, true permanent storage is impossible because of cookies The 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! <br>Put the session into mysql Example: <br>Create a table in the database: session (sesskey varchar32, expiry int11, value longtext) <br>code: <br>The database has been connected before the code is executed. <br>The code is as follows: <br><div class="codetitle"> <span style="CURSOR: pointer" onclick="doCopy('code55261')"><u>Copy code</u></span> The code is as follows:</div> <div class="codebody" id="code55261"> <br>define('STORE_SESSIONS','mysql'); <br>if (STORE_SESSIONS == 'mysql') { <br>if (!$SESS_LIFE = get_cfg_var('session.gc_maxlifetime')) { <br>$SESS_LIFE = 1440; <br>} <br>function _sess_open($ save_path, $session_name) { <br>// If there is no database connection, you can execute mysql_pconnect, mysql_select_db here <br>return true; <br>} <br>function _sess_close() { <br>return true; <br> } <br>function _sess_read($key) { <br>$value_query = mysql_query("select value from sessions where sesskey = '" .addslashes($key) . "' and expiry > '" . time() . " '"); <br>$value = mysql_fetch_array($value_query); <br>if (isset($value['value'])) { <br>return $value['value']; <br>} <br>return false; <br>} <br>function _sess_write($key, $val) { <br>global $SESS_LIFE; <br>$expiry = time() + $SESS_LIFE; <br>$value = $val ; <br>$check_query = mysql_query("select count(*) as total from sessions where sesskey = '" . addslashes($key) . "'"); <br>$check = mysql_fetch_array($check_query); <br>if ($check['total'] > 0) { <br>return mysql_query("update sessions set expiry = '" . addslashes($expiry) . "', value = '" . addslashes($value) . "' where sesskey = '" . addslashes($key) . "'"); <br>} else { <br>return mysql_query("insert into sessions values ​​('" . addslashes($key) . "', ' " . addslashes($expiry) . "', '" . addslashes($value) . "')"); <br>} <br>} <br>function _sess_destroy($key) { <br>return mysql_query( "delete from sessions where sesskey = '" . addslashes($key) . "'"); <br>} <br>function _sess_gc($maxlifetime) { <br>mysql_query("delete from sessions where expiry < '" . time() . "'"); <br>return true; <br>} <br>session_set_save_handler('_sess_open', '_sess_close', '_sess_read', '_sess_write', '_sess_destroy', '_sess_gc'); <br>} <br>danoo_session_name( 'dtvSid' ); <br>danoo_session_save_path(SESSION_WRITE_DIRECTORY); <br> </div> <br>I still don’t understand where the open and write parameters come from. <br>Two commonly used functions to modify php.ini configuration: <br>get_cfg_var('session.gc_maxlifetime') : Get the value of session.gc_maxlifetime <br>ini_set('session.cookie_lifetime','0') : Set session The value of .cookie_lifetime is 0. <p align="left"></p> <div style="display:none;"> <span id="url" itemprop="url">http://www.bkjia.com/PHPjc/323124.html</span><span id="indexUrl" itemprop="indexUrl">www.bkjia.com</span><span id="isOriginal" itemprop="isOriginal">true</span><span id="isBasedOnUrl" itemprop="isBasedOnUrl">http: //www.bkjia.com/PHPjc/323124.html</span><span id="genre" itemprop="genre">TechArticle</span><span id="description" itemprop="description">A known and effective method is to use session_set_save_handler to take over all session management work, usually to store session information Go to the database, so you can delete it through SQL statements...</span> </div> <div class="art_confoot"></div></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="Definition and filling of arrays for PHP learning_PHP tutorial" href="http://m.php.cn/faq/309397.html">Definition and filling of arrays for PHP learning_PHP tutorial</a></span><span>Next article:<a class="dBlack" title="Definition and filling of arrays for PHP learning_PHP tutorial" href="http://m.php.cn/faq/309399.html">Definition and filling of arrays for PHP learning_PHP tutorial</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="http://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ul class="nphpXgwzList"><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/1.html" title="How to use cURL to implement Get and Post requests in PHP" class="aBlack">How to use cURL to implement Get and Post requests in PHP</a><div class="clear"></div></li><li><b></b><a href="http://m.php.cn/faq/2.html" title="All expression symbols in regular expressions (summary)" class="aBlack">All expression symbols in regular expressions (summary)</a><div class="clear"></div></li></ul></div></div><div class="nphpFoot"><div class="nphpFootBg"><ul class="nphpFootMenu"><li><a href="http://m.php.cn/"><b class="icon1"></b><p>Home</p></a></li><li><a href="http://m.php.cn/course.html"><b class="icon2"></b><p>Course</p></a></li><li><a href="http://m.php.cn/wenda.html"><b class="icon4"></b><p>Q&A</p></a></li><li><a href="http://m.php.cn/login"><b class="icon5"></b><p>My</p></a></li><div class="clear"></div></ul></div></div><div class="nphpYouBox" style="display: none;"><div class="nphpYouBg"><div class="nphpYouTitle"><span onclick="$('.nphpYouBox').hide()"></span><a href="http://m.php.cn/"></a><div class="clear"></div></div><ul class="nphpYouList"><li><a href="http://m.php.cn/"><b class="icon1"></b><span>Home</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/course.html"><b class="icon2"></b><span>Course</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/article.html"><b class="icon3"></b><span>Article</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/wenda.html"><b class="icon4"></b><span>Q&A</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/dic.html"><b class="icon6"></b><span>Dictionary</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/course/type/99.html"><b class="icon7"></b><span>Manual</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/xiazai/"><b class="icon8"></b><span>Download</span><div class="clear"></div></a></li><li><a href="http://m.php.cn/faq/zt" title="Topic"><b class="icon12"></b><span>Topic</span><div class="clear"></div></a></li><div class="clear"></div></ul></div></div><div class="nphpDing" style="display: none;"><div class="nphpDinglogo"><a href="http://m.php.cn/"></a></div><div class="nphpNavIn1"><div class="swiper-container nphpNavSwiper1"><div class="swiper-wrapper"><div class="swiper-slide"><a href="http://m.php.cn/" >Home</a></div><div class="swiper-slide"><a href="http://m.php.cn/article.html" class="hover">Article</a></div><div class="swiper-slide"><a href="http://m.php.cn/wenda.html" >Q&A</a></div><div class="swiper-slide"><a href="http://m.php.cn/course.html" >Course</a></div><div class="swiper-slide"><a href="http://m.php.cn/faq/zt" >Topic</a></div><div class="swiper-slide"><a href="http://m.php.cn/xiazai" >Download</a></div><div class="swiper-slide"><a href="http://m.php.cn/game" >Game</a></div><div class="swiper-slide"><a href="http://m.php.cn/dic.html" >Dictionary</a></div><div class="clear"></div></div></div><div class="langadivs" ><a href="javascript:;" class="bg4 bglanguage"></a><div class="langadiv" ><a onclick="javascript:setlang('zh-cn');" class="language course-right-orders chooselan " href="javascript:;"><span>简体中文</span><span>(ZH-CN)</span></a><a onclick="javascript:;" class="language course-right-orders chooselan chooselanguage" href="javascript:;"><span>English</span><span>(EN)</span></a><a onclick="javascript:setlang('zh-tw');" class="language course-right-orders chooselan " href="javascript:;"><span>繁体中文</span><span>(ZH-TW)</span></a><a onclick="javascript:setlang('ja');" class="language course-right-orders chooselan " href="javascript:;"><span>日本語</span><span>(JA)</span></a><a onclick="javascript:setlang('ko');" class="language course-right-orders chooselan " href="javascript:;"><span>한국어</span><span>(KO)</span></a><a onclick="javascript:setlang('ms');" class="language course-right-orders chooselan " href="javascript:;"><span>Melayu</span><span>(MS)</span></a><a onclick="javascript:setlang('fr');" class="language course-right-orders chooselan " href="javascript:;"><span>Français</span><span>(FR)</span></a><a onclick="javascript:setlang('de');" class="language course-right-orders chooselan " href="javascript:;"><span>Deutsch</span><span>(DE)</span></a></div></div><script> var swiper = new Swiper('.nphpNavSwiper1', { slidesPerView : 'auto', observer: true,//修改swiper自己或子元素时,自动初始化swiper observeParents: true,//修改swiper的父元素时,自动初始化swiper }); </script></div></div><!--顶部导航 end--><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) { var _times = times || -1, //100次 _interval = interval || 20, //20毫秒每次 _self = this, _selector = this.selector, //选择器 _iIntervalID; //定时器id if( this.length ){ //如果已经获取到了,就直接执行函数 func && func.call(this); } else { _iIntervalID = setInterval(function() { if(!_times) { //是0就退出 clearInterval(_iIntervalID); } _times <= 0 || _times--; //如果是正数就 -- _self = $(_selector); //再次选择 if( _self.length ) { //判断是否取到 func && func.call(_self); clearInterval(_iIntervalID); } }, _interval); } return this; } $("table.syntaxhighlighter").wait(function() { $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>"); }); $(document).on("click", ".cnblogs_code_footer",function(){ $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide(); }); $('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}}); </script></body></html>