PHP session過期機制和配置/session回收
Posted by feng on 2010/05/11 Leave a comment (0)Go to comments
使用PHP session時會遇到明明超過了session過期時間,但session依然完好無損的活著,讓人頭大。其實仔細(xì)看一下php.ini關(guān)于PHP session回收機制就一目了然了。
session 回收機制:
PHP采用Garbage Collection process對過期session進(jìn)行回收,然而并不是每次session建立時,都能夠喚起 ‘garbage collection’ process ,gc是按照一定概率啟動的。這主要是出于對服務(wù)器性能方面的考慮,每個session都觸發(fā)gc,瀏覽量大的話,服務(wù)器吃不消,然而按照一定概率開啟 gc,當(dāng)流覽量大的時候,session過期機制能夠正常運行,而且服務(wù)器效率得到節(jié)省。細(xì)節(jié)應(yīng)該都是多年的經(jīng)驗積累得出的。
三個與PHP session過期相關(guān)的參數(shù)(php.ini中):
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
gc啟動概率 = gc_probability / gc_divisor = 0.1%
session過期時間 gc_maxlifetime 單位:秒
建議:
自己測試時,當(dāng)然把這個session過期概率設(shè)置越大越好,過期效果才明顯。
當(dāng)web服務(wù)正式提供時,session過期概率就需要根據(jù)web服務(wù)的瀏覽量和服務(wù)器的性能來綜合考慮session過期概率。為每個 session都開啟gc,顯然是很不明智的。
變通方法:
手動在代碼中為session設(shè)定上次訪問時間,并且每次訪問的時候判斷訪問間隔是否超過時間限制,超過手動銷毀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
更多信息請查看IT技術(shù)專欄