我們都知道php有自己的一個預設session機制,就是你不設定任何
session.handler的時候,它會用在臨時目錄下面隱藏檔名類似
sess_5pjm50b8d40p4175iousv4hqd3的一堆session檔案,但是session是有到期時間的,而這些檔案顯然不能無限增多,那麼當session到期以後這些檔案會被回收嗎?是通過什麼機制回收的呢?顯然php本身幹不了這個事情,因為它的生命週期在指令碼執行完就結束了,沒有長駐記憶體的程式來回收這些檔案,難道就放任不管嗎?
回複內容:
我們都知道php有自己的一個預設session機制,就是你不設定任何session.handler的時候,它會用在臨時目錄下面隱藏檔名類似sess_5pjm50b8d40p4175iousv4hqd3的一堆session檔案,但是session是有到期時間的,而這些檔案顯然不能無限增多,那麼當session到期以後這些檔案會被回收嗎?是通過什麼機制回收的呢?顯然php本身幹不了這個事情,因為它的生命週期在指令碼執行完就結束了,沒有長駐記憶體的程式來回收這些檔案,難道就放任不管嗎?
在php.ini中可以看到以下配置行
; Define the probability that the 'garbage collection' process is started; on every session initialization.; The probability is calculated by using gc_probability/gc_divisor,; e.g. 1/100 means there is a 1% chance that the GC process starts; on each request.session.gc_probability = 1session.gc_divisor = 100; After this number of seconds, stored data will be seen as 'garbage' and; cleaned up by the garbage collection process.session.gc_maxlifetime = 1440
從注釋可以看出是session記憶體回收的配置。 session.gc_probability/session.gc_divisor 表述有1%的機率回收大於session.gc_maxlifetime時間的到期檔案。
-----------------------------------------------------------------------------
我們看 http://cn.php.net/manual/zh/sessionha... php文檔對 session.gc 的說明
Cleans up expired sessions. Called randomly by PHP internally when a sessio starts or when session_start() is invoked. The frequency this is called is based on the session.gc_divisor and session.gc_probability configuration directives.This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().If this class is extended by inheritiance, calling the parent gc method will invoke the wrapper for this method and therefor invoke the associated internal callback. This allows this method to be overidden and or intercepted and filtered.For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::gc().
即:比如session_start()一次會話請求,會有1%的機率調用session的記憶體回收來以清理到期會話。
session.gcprobability = 1
session.gcdivisor = 100
session.gc_maxlifetime = 1440
這三個配置組合構建服務端session的記憶體回收機制
session.gc_probability與session.gc_divisor構成執行session清理的機率,理論上的解釋為服務端定期有一定的機率調用gc函數來對session進行清理,清理的機率為:
gc_probability/gc_divisor 比如:1/100 表示每一個新會話初始化時,有1%的機率會啟動記憶體回收程式,清理的標準為session.gc_maxlifetime定義的時間。
我寫了一篇關於結合http分析php session 本質的文章,有興趣的話可以看下 - 你必須瞭解的session的本質