標籤:
問題:使用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記憶體回收機制防止記憶體溢出
PHP session到期機制和配置