Menu

1 / 2

Cache-busting JSON in PHP with filemtime

DEV Community·Odilon HUGONNOT·6 months ago
#RUcTD4FF
#why#php#javascript#cache#file
Reading 0:00
15s threshold

The blog listing loads articles via fetch('posts.json') . Problem: the browser caches this file. When you publish a new article, visitors keep seeing the old list until they manually clear their cache — which they never do.

Why the browser caches the JSON

Without an explicit Cache-Control directive, Apache applies a heuristic: it estimates a cache duration from the file's Last-Modified header. In practice, browsers can keep the file cached for several hours, or even several days depending on their own rules.

You could solve this server-side with an HTTP header:

<FilesMatch "posts\.json$"> Header set Cache-Control "no-cache, must-revalidate" </FilesMatch>

Enter fullscreen mode

Exit fullscreen mode

But this requires mod_headers to be enabled on Apache — which isn't guaranteed on shared hosting.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.