Vote Charlie!

Simple PHP file caching

Posted at age 23.
Created . Edited .

Note to self that might be useful for others doing really basic stuff:

Often I use Random Web Service’s API to get a JSON file of data repeatedly, but that file doesn’t need to be refreshed 600 times a second. I can then use a simple PHP script to store the file and retrieve it from disk until it gets to be a certain age.

For instance, this code will retrieve the file from disk until it is more than 10 minutes old, and then it actually makes another API call for new data.

<?php

$max_age_seconds = 60*10;
$json_file = dirname(__FILE__).'/'.pathinfo(__FILE__,PATHINFO_FILENAME).'.json';
$data;
if( file_exists( $json_file ) && time() - filemtime( $json_file ) < $max_age_seconds ) {
  $data = file_get_contents( $json_file );
} else {
  // Create $data by calling API, etc.
  $data = '';
  file_put_contents( $json_file, $data );
}
$json_decoded = json_decode( $data, true );

?>