彻底解决PHP Session不过期以及SessionId保持不变的问题
用过asp.net里面的session再用过php里面的session,你会觉得php 的session相比asp.net里面的session是如此的不爽。在用php的session,你可能会遇到session不失效,关掉浏览器session还存在,重新打开浏览器sessionid还和以前一样等问题。。。
下面我们就来看下php的session机制:
session 回收机制:
PHP采用Garbage Collection process对过期session进行回收,然而并不是每次session建立时,都能够唤起 ‘garbage collection’ process ,gc是按照一定概率启动的。这主要是出于对服务器性能方面的考虑,每个session都触发gc,浏览量大的话,服务器吃不消,然而按照一定概率开启gc,当流览量大的时候,session过期机制能够正常运行,而且服务器效率得到节省。细节应该都是多年的经验积累得出的。
三个与PHP session过期相关的参数(php.ini中):
session.gc_probability = 1 session.gc_divisor = 1000 session.gc_maxlifetime = 1440
gc启动概率 = gc_probability / gc_divisor = 0.1%
session过期时间 gc_maxlifetime 单位:秒
当web服务正式提供时,session过期概率就需要根据web服务的浏览量和服务器的性能来综合考虑session过期概率。为每个session都开启gc,显然是不明智的,感觉有点“碰运气”的感觉,要是访问量小命中几率就小。我在本机测试过程中,几乎都没有被命中过,sessionid几天都不变,哪怕机器重启。测试过程中,这个过期概率值要设置大一点命中几率才高点。
通过修改php配置文件的过期概率值,可以“碰运气”式的设置session过期,那有没有更好的办法呢?
下面写的这个session类可以彻底解决session不过期以及sessionid不变的问题。
/** * 扩展Session类(简单封装) * * @author slimboy * */ class Session { /** * 初始化 */ static function _init(){ ini_set('session.auto_start', 0); //Session::start(); } /** * 启动Session */ static function start() { session_start(); } /** * 设置Session * * @param $name Session名称 * @param $value 值 * @param $time 超时时间(秒) */ public static function set($name,$value,$time){ if(empty($time)){ $time = 1800; //默认值 } $_SESSION[$name] = $value; $_SESSION[$name.'_Expires'] = time() + $time; } /** * 获取Session值 * * @param $name Session名称 */ public static function get($name){ //检查Session是否已过期 if(isset($_SESSION[$name.'_Expires']) && $_SESSION[$name.'_E xpires']>time()){ return $_SESSION[$name]; }else{ Session::clear($name); return null; } } /** * 设置Session Domain * * @param $sessionDomain 域 * @return string */ static function setDomain($sessionDomain = null) { $return = ini_get('session.cookie_domain'); if(!empty($sessionDomain)) { ini_set('session.cookie_domain', $sessionDomain);//跨 域访问Session } return $return; } /** * 清除某一Session值 * * @param $name Session名称 */ static function clear($name){ unset($_SESSION[$name]); unset($_SESSION[$name.'_Expires']); } /** * 重置销毁Session */ static function destroy(){ unset($_SESSION); session_destroy(); } /** * 获取或设置Session id */ static function sessionid($id=null){ return session_id($id); } }
简单调用:
//设置session Session::set('UserId', $userid, 3600); //读取session $userId = Session::get('UserId');

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

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),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor
