问题:使用PHP session时会遇到明明超过了session过期时间,但session依然完好无损的活着,让人头大。

其实仔细看一下php.ini关于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 ,单位:秒

建议:

自己测试时,当然把这个session过期概率设置越大越好,过期效果才明显。

当web服务正式提供时,session过期概率就需要根据web服务的浏览量和服务器的性能来综合考虑session过期概率。为每个session都开启gc,显然是很不明智的。

变通方法:

手动在代码中为session设定上次访问时间,并且每次访问的时候判断访问间隔是否超过时间限制,超过手动销毁session,未超过则更新上次访问时间。这种方法还可以限制两次访问间隔。

配置文件摘录(来自php.ini),英文的原汁儿原味儿

; Defines the probability that the 'garbage collection' process is started
; on every session initialization. The probability is calculated by using
; gc_probability/gc_divisor. Where session.gc_probability is the numerator
; and gc_divisor is the denominator in the equation. Setting this value to 1
; when the session.gc_divisor value is 100 will give you approximately a 1% chance
; the gc will run on any give request.
; Default Value: 1
; Development Value: 1
; Production Value: 1
; http://php.net/session.gc-probability
session.gc_probability = 1

; Defines the probability that the 'garbage collection' process is started on every
; session initialization. The probability is calculated by using the following equation:
; gc_probability/gc_divisor. Where session.gc_probability is the numerator and
; session.gc_divisor is the denominator in the equation. Setting this value to 1
; when the session.gc_divisor value is 100 will give you approximately a 1% chance
; the gc will run on any give request. Increasing this value to 1000 will give you
; a 0.1% chance the gc will run on any give request. For high volume production servers,
; this is a more efficient approach.
; Default Value: 100
; Development Value: 1000
; Production Value: 1000
; http://php.net/session.gc-divisor
session.gc_divisor = 1000

; After this number of seconds, stored data will be seen as 'garbage' and
; cleaned up by the garbage collection process.
; http://php.net/session.gc-maxlifetime
session.gc_maxlifetime = 1440

 

 

 延伸阅读:

PHP垃圾回收机制防止内存溢出