PHP Script to download multiple files concurrently

This script will show you an example of how to download multiple files concurrently
using the curl_multi commands in PHP 5.While php itself doesn’t support multi threading and concurrency,
libcurl does and php allows us to download multiple files at the same time from php.

 Script Author – JeenaJoy
<?php//This script will show you an example of how to download multiple files concurrently
//using the curl_multi commands in PHP 5.While php itself doesn’t support multi threading and concurrency,
//libcurl does and php allows us to download multiple files at the same time from php.// Files to download
$urls = array(‘http://abc.com/docs/cdbwpohq0ayey.pdf’,
‘http://abc.com/docs/8wyxlxfufftas.pdf’,
‘http://abc.com/docs/9q29bbglnc2gk.pdf’,);

$save_to=’/tmp/';  // Path to save files in

$mh = curl_multi_init();
// Add curl multi handles
foreach ($urls as $i => $url) {

// Path to save files in
$g=$save_to.basename($url);

$conn[$i]=curl_init($url);
$fp[$i]=fopen ($g, “wb”);

curl_setopt ($conn[$i], CURLOPT_HEADER ,0);///it should come first
curl_setopt ($conn[$i], CURLOPT_FILE, $fp[$i]);
curl_multi_add_handle ($mh,$conn[$i]);

}
// Download the files
do {
$n=curl_multi_exec($mh,$active);
}
while ($active);
foreach ($urls as $i => $url)
{
curl_multi_remove_handle($mh,$conn[$i]);

curl_close($conn[$i]);
fclose ($fp[$i]);

}
curl_multi_close($mh);

?>

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>