Magento – Magento form key invalid after page becomes inactive for extended period of time

ce-1.9.1.0form-keysession

Running a recently upgraded instance of Magento CE 1.9.1.0 (from 1.7.0.2). Form key support was built in to the theme and is functioning a-okay when browsing the website with different browsers and caching enabled.

I have noticed however that if a single browser leaves a page open for an extended period of time (roughly 2 – 3 hours), upon resuming activity on that page and clicking the add to cart button does not work the first time it is clicked. The cart is still empty but after a page refresh it becomes functional again.

I'm assuming that this is because the form-key rendered on the page at the time it was generated and output to HTML is no longer the same as what Magento's core/session model references in the database. After the page refresh this resolves itself.

Has anyone else experienced this? Is there a way to resolve this issue?

Best Answer

Presumably that's because the visitor's session expired. The form key is tied to the session. When they submit the form, Magento sees they have no valid session, and so creates a new one (along with a new form key). That new key doesn't match the one submitted, so they get an error--but submitting again immediately after that failure would indeed work.

Solution? Raise your session lifetime.

  1. Make sure cookies are staying around (I would recommend expiration date of a day or more). See: System > Configuration > Web > Session Cookie Management > Cookie Lifetime
  2. Make sure PHP isn't cleaning out sessions prematurely. That means increasing the value of PHP setting session.gc_maxlifetime (by default, set to 24 minutes). You may have to contact your host to arrange this.