You are here

5 January 2016

When you create a simple request without any special REST client, you can do it just by using curl. When you need to do curl request, it's not a good practise to do it on every page load. So the results should be cached.

Source code viewer
  1. // Set error reporting level.
  2. error_reporting(E_ALL|E_STRICT);
  3.  
  4. // Parameters.
  5. $username = '';
  6. $password = '';
  7. $location = 'https://browse-tutorials.com';
  8. $query = array(
  9. 'limit' => 20,
  10. );
  11. $cacheFileName = 'json.cache.txt';
  12. $cacheUpdateMin = 30;
  13.  
  14. $results = array();
  15. // Check if the file exists and file timestamp against current time.
  16. if (!file_exists($cacheFileName) || filemtime($cacheFileName) + ($cacheUpdateMin * 60) < time()) {
  17. // Curl request to get the json.
  18. $ch = curl_init();
  19. curl_setopt($ch, CURLOPT_URL, $location . '?' . http_build_query($query));
  20. curl_setopt($ch, CURLOPT_HEADER, 0);
  21. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  22. curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
  23. $contents = curl_exec($ch);
  24. curl_close($ch);
  25. // Write to the cache file.
  26. file_put_contents($cacheFileName, $contents);
  27. // Decode the results.
  28. $results = json_decode($contents);
  29. }
  30. else {
  31. // Load the results directly from cache.
  32. $results = json_decode(file_get_contents($cacheFileName));
  33. }
  34.  
  35. print_r($results); exit;
Programming Language: PHP