Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Multiple curl requests

Here is function that performs multiple curl requests which is much faster then file_get_contents or single curl request. For more information http://webcodingeasy.com/Site-optimization/Comparing-filegetcontents-with-curl-and-curl-multi-handlers

It takes array of URLs to request as a parameter and returns array of contents or errors for each url:

<?php
//$urls - array of urls to request
function multi_curl($urls){
    // for curl handlers
    $curl_handlers = array();

    //for storing contents
    $content = array();
    //setting curl handlers
    foreach ($urls as $url) 
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $curl_handlers[] = $curl;
    }
    //initiating multi handler
    $multi_curl_handler = curl_multi_init();

    // adding all the single handler to a multi handler
    foreach($curl_handlers as $key => $curl)
    {
        curl_multi_add_handle($multi_curl_handler,$curl);
    }
    
    // executing the multi handler
    do 
    {
        $multi_curl = curl_multi_exec($multi_curl_handler, $active);
    } 
    while ($multi_curl == CURLM_CALL_MULTI_PERFORM  || $active);
    
    foreach($curl_handlers as $curl)
    {
        //checking for errors
        if(curl_errno($curl) == CURLE_OK)
        {
            //if no error then getting content
            $content[] = curl_multi_getcontent($curl);
            //parsing content
        }
        else
        {
            //storing error
            $content[] = curl_error($curl);
        }
    }
    curl_multi_close($multi_curl_handler);
    return $content;
}   

$arr = multi_curl(array("http://cms.annar2r.info/server.php", 
                        "http://code-snippets.co.cc/", 
                        "annar2r.info"));
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus