本文實例講述了PHP編程中的Session阻塞問題與解決方法。分享給大家供大家參考,具體如下:
使用session過程中,在開啟session后,同一瀏覽器,執行同一程序,不同頁面會被鎖。不同瀏覽器不會出現這種情況。
疑問:是不是session_start導致了阻塞?
于是,我寫了幾個頁面測試了一下,發現是session導致了阻塞,而其他兩種情況不會造成阻塞。
查了下PHP的Bug列表,發現有人提出了這個問題:
Description:
------------
Calling session_start() appears to wait until other scripts have exited
that are using the same session. My guess is the 1st request locks the
session file for exclusive use, and the second request blocks until it
can open it.
PHP官方的回復是:
Thank you for taking the time to write to us, but this is not a bug.This is expected, the session file is locked to avoid corruption.
結合了PHP的Session機制,找到了阻塞的原因。由于PHP的Session信息是寫入文件的,1個客戶端占有1個session文件。因此,當 session_start被調用的時候,該文件是被鎖住的,而且是以讀寫模式鎖住的(因為程序中可能要修改session的值),這樣,第2次調用 session_start的時候就被阻塞了。
最簡解決方法:
查了PHP的手冊,發現一個session_write_close函數,作用是Write session data and end session,也就是寫session的數據,同時關閉這個session。因此,我們可以在用完session之后,調用這個函數關閉session 文件即可解除鎖定。一般,session是用來記錄用戶身份信息的,以便PHP進行身份認證,因此完全可以將session的讀寫放在頁面剛開始執行的時 候,在執行完以后,馬上調用session_write_close函數即可。
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP中cookie用法總結》、《PHP數組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php面向對象程序設計入門教程》、《PHP網絡編程技巧總結》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。