Adjusting PHP pages to work with full caching

Caching web pages speeds-up dramatically the loading time. A ready, waiting cached version is served, no load on the server, no preparation, here it is!

Pages are usually created dynamically: the system takes a common header and footer, adds content from the database and serves a complete page for the URL. The same URL will usually serve the same page (until the content is updated). These pages are easy to fully cache – the final rendered page is cached and served as is to all the visitors of the site.

Some pages, or elements of the page, will share the same URL, but serve different content based on the visitor’s geography, cookies, browser, or other parameters. Several examples could be: showing different prices to visitors from different countries, showing a GDPR banner only to visitors from the EU, or showing promotions based on a cookie stored on the visitors computer. If these variations are created on the server side (let’s say using PHP) then when cached, only one version will be cached and served to all the visitors.

How can we keep the dynamic elements and still enjoy the caching speed boost?

JavaScript, along with images, CSS, and html are cached, but JavaScript runs in the browser and could produce different end results for the user. Our solution will be to move some or all of the logic to JavaScript and combine AJAX calls to non cached PHP pages for additional services.

Let’s take a simple example of GDPR regulation, showing a banner to EU visitors and only if they accept the terms, we load analytics and other 3rd party scripts.

In a PHP based script we check the IP with an external service to get the visitor’s country. As soon as we have the country we check if it is part of the GDPR regulation and show the GDPR banner. If they accept the terms we load the scripts.
If fully cached the system will take a single version of the rendered webpage (say non-GDPR) and will show it always no matter what the IP or who the visitor is.

In a JavaScript version we will AJAX call a non cached PHP file which will check the country of the IP and if it’s GDPR, and return a response to the script. The script will continue the logic based on the response. This could be fully cached since JavaScript will run cached and the AJAX call will be done at the end of the page load, without harming load time and responsiveness. Of course, you can implement the entire code in JavaScript, without PHP, but then the entire logic is exposed and you are building from scratch, instead of leveraging existing code.

In the PHP file you return content to JavaScript simply by outputting it with echo()

Let me know if you used the above technique, or other ways you leverage cache.

Leave a Reply

Your email address will not be published. Required fields are marked *