Laravel 5.1 randomly dropping session data

2019-06-18 15:10发布

I have a strange issue with a Laravel 5.1 application.

Intermittently, it’s dropping session data. I’m detected this by writing some middleware that writes the contents of the session for that request to the log file. Although the session ID (Session::getId()) doesn’t change, the value of _token in the session data retrieved with Session::all() does.

As I say, this happens intermittently. I can refresh the same URL multiple times, and then randomly on one refresh the session data’s gone, and the _token value’s different from the previous requests.

What would cause this? I’ve also noticed the flash object isn’t in the “dropped” session data.

Below is a snippet of the log. You can see the content of the session_data key randomly changes “shape” in the last two lines, but the session ID remains constant.

Also, not sure if it’s pertinent, but I have DebugBar enabled.

Screen-shot

UPDATE: Through debugging, I’ve found that on some page loads the session is completely empty, as in, no _token (hence a new one getting generated). Nothing.

2条回答
手持菜刀,她持情操
2楼-- · 2019-06-18 15:37
  1. If you're using the file driver, you could run into race conditions on concurrent requests. The file then gets truncated, Laravel can't read it, so it refreshes the session. Race conditions can also lead to a symptom where something you're putting to the session just doesn't get put. This tends to be random, so it's very hard to debug. According to the Laravel team, this is a known limitation of the file driver and it does not appear to be getting fixed, so I would suggest using a different driver. This would fix your issue of random session refreshes, but it still introduces a possibility of making a change to the session that doesn't get added. As far as I know, at this point with Laravel 5.1, you'll have to manage that yourself.

  2. Somehow your session data is too long and being truncated. If you're using the database driver (haven't tested other drivers), and you try to save session data that's longer than the field length, then subsequent requests won't be able to pull from this session, and you'll wind up with a new session. If this issue is happening randomly with very short session data, then it's probably the cause listed above.

查看更多
混吃等死
3楼-- · 2019-06-18 15:37

If you use Linux, Try using Redis (http://redis.io) as session / cache manager in laravel. I had some issues in the past with text / cookies and laravel in some servers. When I instaled Redis I had no problems anymore.

More info: https://laravel.com/docs/5.1/redis

查看更多
登录 后发表回答