Laravel 5.5+PHP7.1环境下长时间停留页面后POST请求发送问题咨询
Absolutely, this is a plausible scenario—let’s break down the key factors that could cause your POST request to fail, tailored to your tech stack:
Key Factors Determining This Outcome
1. Laravel Session Lifetime Configuration
By default, Laravel 5.5 sets the session lifetime to 120 minutes (check config/session.php for the lifetime value). If you’ve modified this to 60 minutes or less, the user’s session will expire after that window. Since Laravel requires a valid CSRF token (tied to the active session) for all POST requests, an expired session means the CSRF token in your form becomes invalid, triggering a TokenMismatchException and rejecting the request.
2. PHP’s session.gc_maxlifetime Setting
This PHP.ini config controls how long session files (when using the file session driver) are retained before garbage collection. If session.gc_maxlifetime is set to a shorter value than your Laravel lifetime (the default PHP value is often 1440 seconds / 24 minutes), PHP will clean up the session file before Laravel’s intended expiration time. This also leads to an invalid session and failed POST request.
3. Session Driver-Specific Expiry Rules
If you’re using a non-file session driver (like Redis or Memcached), ensure the storage’s TTL (time-to-live) matches your Laravel session lifetime. For example, if Redis is set to expire session keys after 60 minutes but Laravel expects 90, the session will still expire early and break your POST request.
4. Browser/Client-Side Behavior
While less common, some browsers may restrict background tabs from sending requests after extended periods, or if the user’s system goes to sleep. Additionally, if your session cookie is set to a strict expiry time (instead of the default "session" duration), the cookie could expire before the user submits the request—even if the page stays open.
Quick Mitigations
- Extend session settings: Update
config/session.php’slifetimeto at least 90 minutes, and ensuresession.gc_maxlifetimein php.ini is equal to or greater than this value. - Refresh CSRF tokens dynamically: Add a small AJAX script to your page that periodically fetches a new CSRF token (from a simple route like
csrf-token) and updates the_tokenfield in your form. This keeps the token valid even if the session is extended. - Disable CSRF for the test route (carefully): If your test doesn’t require session-based auth, you could exclude the route from CSRF protection (only do this if you’re certain it’s safe for your use case).
内容的提问来源于stack exchange,提问作者user7194542

