Home >Backend Development >PHP Tutorial >How to use infinite lifetime Session_PHP Tutorial

How to use infinite lifetime Session_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 16:07:09915browse

Support for Session has been added to PHP4.0, which facilitates many of our programs, such as shopping carts, etc.!
In many forums, Session is also used to process user logins and record usernames and passwords, so that users do not have to enter their usernames and passwords every time! However, the life span of a general Session is limited. 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 aspects of the Session in php.ini Settings (open the 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 where SessionID is stored. It may be passed by Cookie or Query_String. The default value is "PHPSESSID";
3. Session.cookie_lifetime: This represents that SessionID is stored in the client cookie. The time, 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? Yes...
If you have the operating authority 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 to store SessionID. However, The default is 1 and 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. Change "session. gc_maxlifetime" is set to the same time as "session.cookie_lifetime";
After the setting is completed, open the editor and enter the following code:
----------------- -------------------------------------------------- ------------------
session_start();
session_register('count');
$count++;
echo $count;
?>
----------------------------------------- -----------------------------------------------
Then Save it as "session_check.php", open "session_check.php" with a browser and see if "1" is displayed, then close the browser, then open the browser to visit "session_check.php", if "2" is displayed , then congratulations, you have succeeded; if it fails, please check your previous settings.

But if you don’t 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 (already marked in the figure). This 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>Open the editor and enter the following code: <br>---------------------------------- --------------------------------------------------<br><? <br>session_start(); // Start Session <br>session_register('count'); // Register Session variable Count <br>if(isset($PHPSESSID)) { <br>session_id($ PHPSESSID); <br>} // If $PHPSESSID is set, assign SessionID to $PHPSESSID, otherwise generate SessionID <br>$PHPSESSID = session_id(); // Get the current SessionID <br>$count++; // Add 1 to variable count <br>setcookie('PHPSESSID', $PHPSESSID, time()+3156000); // Store SessionID in Cookie <br>echo $count; // Display the value of Session variable count <br>?> ; <br>------------------------------------------------ --------------------------------------------- <br><br>After saving, use the same The same method is used to detect when you have server permissions, and check whether the SessionID is successfully saved. <br><br><br>Postscript: <br>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 stored for a long time, The above method is enough! For other applications of Session, please see the article on zphp.com. <br>Finally, the author’s debugging environment: Windows98DigExt(SE)+Apache+PHP 4.04. <br><br> </p> <p align="left"></p> <div style="display:none;"> <span id="url" itemprop="url">http://www.bkjia.com/PHPjc/315198.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/315198.html</span><span id="genre" itemprop="genre">TechArticle</span><span id="description" itemprop="description">Added support for Session in PHP4.0, which facilitates many of our programs, such as shopping carts, etc.! In many forums, Session is also used to process user logins and record usernames and passwords...</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="PHP counter program_PHP tutorial" href="https://m.php.cn/faq/312141.html">PHP counter program_PHP tutorial</a></span><span>Next article:<a class="dBlack" title="PHP counter program_PHP tutorial" href="https://m.php.cn/faq/312143.html">PHP counter program_PHP tutorial</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="https://m.php.cn/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ins class="adsbygoogle" style="display:block" data-ad-format="fluid" data-ad-layout-key="-6t+ed+2i-1n-4w" data-ad-client="ca-pub-5902227090019525" data-ad-slot="8966999616"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><ul class="nphpXgwzList"><li><b></b><a href="https://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="https://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="https://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="https://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="https://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><ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5902227090019525" data-ad-slot="5027754603"></ins><script> (adsbygoogle = window.adsbygoogle || []).push({}); </script><footer><div class="footer"><div class="footertop"><img src="/static/imghwm/logo.png" alt=""><p>Public welfare online PHP training,Help PHP learners grow quickly!</p></div><div class="footermid"><a href="https://m.php.cn/about/us.html">About us</a><a href="https://m.php.cn/about/disclaimer.html">Disclaimer</a><a href="https://m.php.cn/update/article_0_1.html">Sitemap</a></div><div class="footerbottom"><p> © php.cn All rights reserved </p></div></div></footer><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><!-- Matomo --><script> var _paq = window._paq = window._paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="https://tongji.php.cn/"; _paq.push(['setTrackerUrl', u+'matomo.php']); _paq.push(['setSiteId', '9']); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s); })(); </script><!-- End Matomo Code --></html>