Search code examples
phpjsonfile-get-contentsfile-put-contentscache-expiration

Caching JSON on server using expiration date?


This is some working code that I wrote to call a JSON file and cache it on my servers.

I'm calling the cached file. If the file exists I use json_decode on it. If the file doesn't exist I then call the JSON and decode that. Then after calling the JSON url, I write the contents to the cached file url.

$cache = @file_get_contents('cache/'.$filename.'.txt');

 //check to see if file exists:
if (strlen($cache)<1) {

    // file is empty
    echo '<notcached />';
    $JSON1= @file_get_contents($url);

    $JSON_Data1 = json_decode($JSON1);

    $myfile = fopen('cache/'.$filename.'.txt', "w");
    $put = file_put_contents('cache/'.$filename.'.txt', ($JSON1));

} else {

    //if file doesn't exist:
    $JSON_Data1 = json_decode($cache);
    echo '<cached />';
}

Instead of only using if (strlen($cache)<1) {, is there a way that I can check the age of the $filename.txt and if it's older than 30 days grab the JSON url in the else statement?


Solution

  • You can use something like

    $file = 'cache/'.$filename.'.txt';
    $modify = filemtime($file);
    //check to see if file exists:
    if ($modify == false || $modify < strtotime('now -30 day')) {
        // file is empty, or too old
        echo '<notcached />';
    } else {
        // Good to use file
        echo '<cached />';
    }
    

    filemtime() returns the last modified time of the file, the if statement checks that the file exists (filemtime returns false if it fails) or the file was last modified more than 30 days ago.

    OR... to check if the file exists or too old (without warnings)

    $file = 'cache/'.$filename.'.txt';
    if (file_exists($file) == false || filemtime($file) < strtotime('now -30 day')) {
        // file is empty, or too old
        echo '<notcached />';
    } else {
        // Good to use file
        echo '<cached />';
    }