PHP - Session file và Ajax request

Tình huống:

Vấn đề:

Nguyên nhân:

PHP writes its session data to a file by default. When a request is made to a PHP script that starts the session (session_start()), this session file is locked. What this means is that if your web page makes numerous requests to PHP scripts, for instance, for loading content via Ajax, each request could be locking the session and preventing the other requests from completing.

The other requests will hang on session_start() until the session file is unlocked. This is especially bad if one of your Ajax requests is relatively long-running.

Khi nhận được request, nếu có gọi hàm session_start(), file session sẽ bị lock lại, và chỉ được unlock khi nó xử lý xong, dẫn đễn các request (mà có sử dụng hàm trên) đều pending cho đến khi process trước đó được xử lý xong (unlock file).

Điều này giải thích khi user click 1 link trên trình duyệt mà trước đó có 1 ajax-request xử lý lâu, cho dù user (trình duyệt) gửi tiếp request về server thì vẫn phải chờ cho đến khi file session được unlock.

Giải quyết:

Sử dụng hàm session_write_close(); để kết thúc việc lock file session và truy cập session file chế độ chỉ đọc (read-only).

session_start();
session_write_close();

Nguồn tham khảo: http://konrness.com/php5/how-to-prevent-blocking-php-requests/

Origin post at https://archive.camratus.com/2016/03/24/php-session-file-va-ajax-request/

Tags:
#php #session #ajax