PHP curl_multi_init Example

One of the extensions I’ve used a lot in PHP is cURL, as it’s a great way to fetch remote documents. Previously I have showed that cURL is much faster than file_get_contents.While curl_init and curl_exec works well and is faster than file_get_contents, it can be quite slow when the need to fetch multiple files arises. For situations where multiple files need to be fetched, curl_multi_init and curl_multi_exec will work better in that it can fetch multiple files simultaneously.

The curl_multi_exec is a very powerful function, but the PHP documentations make it seem like quite a complicated one. Here is a basic demonstration where Google, Yahoo, and Bing are all fetched:

$urls = array('http://www.google.com/', 'http://www.yahoo.com/', 'http://www.bing.com/');
$url_count = count($urls);

$curl_array = array();
$ch = curl_multi_init();

foreach($urls as $count => $url) {
	$curl_array[$count] = curl_init($url);
	curl_setopt($curl_array[$count], CURLOPT_RETURNTRANSFER, 1);
	curl_multi_add_handle($ch, $curl_array[$count]);
}

do {
	curl_multi_exec($ch, $exec);
} while($exec > 0);

In this example, the 3 URLs are all set and fetched at the same time. Even though we are not reading the contents of those three files, we are setting CURLOPT_RETURNTRANSFER to prevent the content of the 3 files from being automatically outputted.

curl_multi_getcontent

In certain cases, we will want to read the content of the 3 files. To read the content of the files, we will use the curl_multi_getcontent function. The example below demonstrates how this can be done (the code below should be appended to the previous example as they work together):

foreach($urls as $count => $url) {
	$returned = curl_multi_getcontent($curl_array[$count]);
	echo "$url - $returned";
}

Closing the cURL Handles

Some PHP coders prefer to execute curl_close after it is used. You should only use curl_close, curl_multi_close, and curl_multi_remove_handle after you have retrieved the content (in the case if you need it). It is demonstrated in the example below:

foreach($urls as $count => $url) {
	curl_multi_remove_handle($ch, $curl_array[$count]);
}

curl_multi_close($ch); 

foreach($urls as $count => $url) {
	curl_close($curl_array[$count]);
}

3 thoughts on “PHP curl_multi_init Example

  1. kamal

    But the code is not working, it is even not fetching the above given urls

    $curl_array[$count] = curl_init($url);
    above line gives error.string expected array given.
    ??

Comments are closed.