mrl22
6/26/2017 - 9:15 AM

Cached cURL Request

Cached cURL Request

function curl2json($url, $header_opts=array(), $cache_life=300) {

    $cache_file = md5($url.json_encode($header_opts)).'.txt';

    if (!file_exists($cache_file) || (time() - filemtime($cache_file)) >= $cache_life) {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_SSL_VERIFYPEER => FALSE,
            CURLOPT_FOLLOWLOCATION => FALSE,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $url,
            CURLOPT_HTTPHEADER => $header_opts
        ));
        $resp = curl_exec($curl);
        file_put_contents($cache_file, $resp);
        curl_close($curl);
        return json_decode($resp, true);
    } else {
        return json_decode(file_get_contents($cache_file), true);
    }

}