Nitin Mistry
Nitin Mistry

Reputation: 59

PHP: file_get_contents() force reading the file from server instead of cache

I am trying to read my constants from a JSON file using

$const = file_get_contents('/myfolder/const.json');

Problem is this will always read the file from cache and not from my local XAMPP server. During development phase, this file is dynamic due to edits and I end up clearing the browser cache everytime there's a change in the file. How can I force to read from the server always (latency in doing this during development phase is fine. I will switch to normal post deployment - how?)? Any help is appreciated.

Upvotes: 2

Views: 3316

Answers (3)

Ikari
Ikari

Reputation: 3246

If you are running a standard webserver like Apache or Nginx, the best idea would be to send a Cache-Control header, just what a browser does.

So, for file_get_contents you'd need to create a context resource like:

$context = [
    'http' => [
        'header' => "Cache-Control: no-cache\r\n" .
            "Pragma: no-cache\r\n"
    ]
];

And finally, the request:

$file = file_get_contents('/myfolder/const.json', false, $context);

Also, it probably isn't a good idea to depend upon the chroot provided by the server. Rather provide an absolute path to the file by __DIR__ . /myfolder/const.json which won't make you have to deal with all the pain with cache invalidation. Or, using something like http:// . $_SERVER['SERVER_ADDR'] . '/myfolder/const.json which would again make you have to deal with all the cache PITA.

Upvotes: 1

thomasw_lrd
thomasw_lrd

Reputation: 546

There are a couple of "accepted" solutions.

The first is to add a timestamp to the file like

$const = file_get_contents('/myfolder/const.json?'.date("Ymdhis"));

You can also try this

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

I suggest adding one of these, clearing your cache and then try to run the code. Adding the timestamp to the file has worked for me, when I add it before I start devving, and reloading the page.

Upvotes: 6

Tarun
Tarun

Reputation: 3165

You could do the following to invalidate cache every time file gets updated

$filePath = "/myfolder/const.json";
$const = file_get_contents($filePath."?k=".filemtime($filePath));

Upvotes: 1

Related Questions