w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Caching Instagram API requests using PHP?

I used below code which is taken from your provided code and it seems to be working fine..

$client = "55447265ed444bb5b768ecb0765ba9cb";  
$query = $_POST['q'];  
$clnum = mt_rand(1,3);

$api =

function get_curl($url) {
    if(function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
        $output = curl_exec($ch);
        echo curl_error($ch);
        return $output;
    } else{
        return file_get_contents($url);

$images = array();

$cache = './cache.json';

if(file_exists($cache) && filemtime($cache) > time() - 60*60){
    // If a cache file exists, and it is newer than 1 hour, use it
    $images = json_decode(file_get_contents($cache),true); //Decode as an
json array
} else {
    // Make an API request and create the cache file
    // For example, gets the 32 most popular images on Instagram
    $response = get_curl($api); //change request path to pull different

    $images = array();

        // Decode the response and build an array
        foreach(json_decode($response)->data as $item){

            $title =

            $src = $item->images->standard_resolution->url;
//Caches standard res img path to variable $src

            //Location coords seemed empty in the results but you would
need to check them as mostly be undefined
            $lat =
// Caches latitude as $lat
            $lon =
// Caches longitude as $lon

            $images[] = array(
                "title" => htmlspecialchars($title),
                "src" => htmlspecialchars($src),
                "lat" => htmlspecialchars($lat),
                "lon" => htmlspecialchars($lon) // Consolidates
variables to an array
            file_put_contents($cache,json_encode($images)); //Save as json

//Debug out
echo "<pre>";

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.