The Conflict
A common issue when developing a website comes when your site has a need for page cache, but also a need for user sessions using cookies. PHP Sessions conflict with page caching, and here’s why:
When a user visits your site, they request a page. The page request is sent to the server, where your PHP code is executed to generate the page. The PHP code is where you’d set any specific PHP Session variables, and also any actions to take place based on the presence of these cookies and sessions. For the first user to your site, this is no problem. The PHP code is requested and executed as normal! But on the way to serve the request to your user, the server stores a copy of the generated HTML in page cache.
Enter the conflict: with page caching, the second user to come to your site within your caching timeframe gets served the cached version of the page. The request never makes it back to WordPress/PHP to process the code again. So your cookies and sessions aren’t set, and your actions based on cookies present aren’t executed.
Decision Time
In this situation, you have to make a decision: Is a cookie or a PHP Session really the right course of action for what you’re trying to accomplish? If the answer is yes, you’ll need to make Page Cache exemptions on your site in order to get things working. This means extra traffic going to this page could cause high server load, and could take longer to process.
If the answer is no, consider other options: Can you perform the action you want with Javascript? Admin-ajax requests? Whenever possible, dynamic content should load with Javascript so that it can still run lightweight on your server, and take advantage of page cache. If this simply isn’t possible, go ahead and uncache the page. But, rest assured that if you use Object Cache to cache repeated query results, at least this caching layer will still be present to cache the results of the queries run on these pages.
Leave a Reply