Question

I'm using cURL to upload a file via given URL. (user gives URL, and my server downloads the file)

For a progressbar, I use the CURLOPT_PROGRESSFUNCTION option. I want the function of the progress to also calculate the speed of download, and how much time left.

$fp = fopen($temp_file, "w");
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOPROGRESS, false );
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, "curl_progress_callback");
curl_setopt($ch, CURLOPT_FILE, $fp);
$success = curl_exec($ch);
$curl_info = curl_getinfo($ch);
curl_close($ch);
fclose($fp);

function curl_progress_callback ($download_size, $downloaded_size, $upload_size, $uploaded_size) {
    global $fileinfo;
    if (!$downloaded_size) {
        if (!isset($fileinfo->size)) {
            $fileinfo->size = $download_size;
            event_callback(array("send" => $fileinfo));
        }
    }
    event_callback(array("progress" => array("loaded" => $downloaded_size, "total" => $download_size)));
}

Thank you! and sorry for my English

Was it helpful?

Solution

Add this before curl_exec:

$startTime = $prevTime = microtime(true);
$prevSize = 0;

You can calculate the average and current speed, and remaining time by adding this to the callback function:

$averageSpeed = $downloaded_size / (microtime(true) - $startTime);

$currentSpeed = ($downloaded_size - $prevSize) / (microtime(true) - $prevTime);
$prevTime = microtime(true);
$prevSize = $downloaded_size;

$timeRemaining = ($downloaded_size - $download_size) / $averageSpeed;

Speed is measured in Bytes/s and remaining time in seconds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top