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

Comparing file_get_contents with curl and curl multi handlers

There is a way to handle multiple HTTP requests using curl. For comparison we will request contents of same url 100 times  and for that we will use 3 different codes, one for file_get_contants, other for simple curl request and last for curl_multi request handling.

Here is a file_get_contents function:

<?php
$domain = "http://code-snippets.co.cc";

for($i=0; $i<=100; $i++)
{
    file_get_contents($domain);
}
?>

Average results are 120 seconds or 1,2 seconds per request

Here is a simple curl request:

<?php

$domain = "http://code-snippets.co.cc";

for($i=0; $i<=100; $i++)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL,$domain);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_exec($curl);
    curl_close($curl);
}

?>

Average results are 100 seconds or 1 second per request

And here it is with multi curl handlers:

<?php
$domain = "http://code-snippets.co.cc";

$curl_handlers = array();
for($i=0; $i<=100; $i++)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $domain);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $curl_handlers[] = $curl;
}

$multi_curl_handler = curl_multi_init();

foreach($curl_handlers as $key => $curl)
{
    curl_multi_add_handle($multi_curl_handler,$curl);
}
    
do 
{
    $multi_curl = curl_multi_exec($multi_curl_handler, $active);
} 
while ($multi_curl == CURLM_CALL_MULTI_PERFORM  || $active);

foreach($curl_handlers as $curl)
{
    curl_multi_getcontent($curl);
}
?>

Average result is 21 second or 0,21 per request.

Conclusion: Curl multi handler is almost six times faster than file_get_contents and 5 times faster than simple curl request. So if you want to handle multiple HTTP requests do it using curl multiple request handler


You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus