Jump to content

Downloading multiple files with cURL


AbdullahAlMamun

Recommended Posts

I have this code and its downloading file nicely. But I want to show a progress bar while downloading file from external server. My existing code shows progress bar but its not effective (ex. if i try to download two media file, one video and another audio, and video size is larger than audio size the audio finishes first and the progress bar shows 100% also suddenly it drops to 50% as the video is still downloading ). I mean it actually shows two progress and I need one. If I could get average percentage value of two progress that would be better. Any suggestion regarding this will be greatly appreciated.

 

<?php
set_time_limit ( 0 );
function define_progress_callback($i) {
global $conn;

curl_setopt($conn[$i], CURLOPT_PROGRESSFUNCTION, function ($resource,$download_size, $downloaded, $upload_size, $uploaded)
{
    if($download_size > 0)
        $progress = round($downloaded / $download_size  * 100);
        echo '<script language="javascript">$(".loader").loader("setProgress", '.$progress.');</script>';
        echo str_pad("",1024," ");
        flush();
        usleep(20000);

});
}

$urls = array("http://example.com/file.mp3",
                "http:/example.com/file.mp4");
$save_to='./tmp/';
$conn = array();
$fp = array();
$mh = curl_multi_init();

    foreach ($urls as $i => $url) {
    $g = $save_to . basename($url);
    $conn[$i]=curl_init($url);
    $fp[$i]=fopen ($g, "wb");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // No certificate
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt ($conn[$i], CURLOPT_FILE, $fp[$i]);
    curl_setopt ($conn[$i], CURLOPT_HEADER ,0);
    curl_setopt($conn[$i],CURLOPT_CONNECTTIMEOUT,60);
    curl_setopt ($conn[$i], CURLOPT_MAXCONNECTS, 10);
    curl_setopt($conn[$i], CURLOPT_NOPROGRESS, false);
    define_progress_callback($i);
    curl_multi_add_handle ($mh,$conn[$i]);
    }

    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);

?>
Link to comment
https://forums.phpfreaks.com/topic/294022-downloading-multiple-files-with-curl/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.