Using Curl with APC

Function to do a curl request or grab results from apc.

Useful when requesting a source that takes to long to grab and does not change very often.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function curl_get_cache($url, $use_cache = false, $cache_ttl = 86400)
{
    if (true == $use_cache)
    {
        $apc_key = 'curl_' . md5($url);
        $apc_fetch = apc_fetch($apc_key);
       
        if ($apc_fetch)
        {
            return $apc_fetch;
        }
    }
   
    $curl_handle = curl_init();

    curl_setopt($curl_handle, CURLOPT_URL, $url);
    curl_setopt($curl_handle, CURLOPT_HEADER, 0);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT_MS, 5000);
    curl_setopt($curl_handle, CURLOPT_TIMEOUT_MS, 5000);

    $result = curl_exec($curl_handle);
   
    if (true == $use_cache)
    {
        apc_store($apc_key, $result, $cache_ttl);
    }

    curl_close($curl_handle);
   
    return $result;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>