title: Facebook Graph API caching JSON response
body: <p>I am using Facebook Graph API to get contents from a Facebook fan page and then display them into a website. I am doing it like this, and it is working, but somehow, it seems that my hosting provider is limiting my requests every certain time.... So I would like to cache the response and only ask for a new request every 8h for example.</p>
  
  <pre><code>$data = get_data("https://graph.facebook.com/12345678/posts?access_token=1111112222233333&amp;limit=20&amp;fields=full_picture,link,message,likes,comments&amp;date_format=U");
  $result = json_decode($data);
  </code></pre>
  
  <p>The get_data function uses CURL in the following way:</p>
  
  <pre><code>function get_data($url) {
      $ch = curl_init();
      $timeout = 5;
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      $datos = curl_exec($ch);
      curl_close($ch);
      return $datos;
  }
  </code></pre>
  
  <p>This works fine, I can output the JSON data response and use it as I like into my website to display the content. But as I mention, in my hosting, this seems to fail every X time, I guess because I am getting limited. I have tried to cache the response using some code I saw here at Stackoverflow. But I cannot figure out how to integrate and use both codes. I have managed to create the cache file, but I cannot manage to read correctly from the cached file and avoid making a new request to Facebook graph API.</p>
  
  <pre><code>// cache files are created like cache/abcdef123456...
      $cacheFile = 'cache' . DIRECTORY_SEPARATOR . md5($url);
  
      if (file_exists($cacheFile)) {
          $fh = fopen($cacheFile, 'r');
          $cacheTime = trim(fgets($fh));
  
          // if data was cached recently, return cached data
          if ($cacheTime &gt; strtotime('-60 minutes')) {
              return fread($fh);
          }
  
          // else delete cache file
          fclose($fh);
          unlink($cacheFile);
      }
  
  $fh = fopen($cacheFile, 'w');
      fwrite($fh, time() . "\n");
      fwrite($fh, $json);
      fclose($fh);
  
  return $json;
  </code></pre>
  
  <p>Many thanks in advance for your help!</p>