doushang1880 2014-04-09 13:11
浏览 268
已采纳

如何使用cURL progress_callback(PHP)计算下载速度

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

  • 写回答

1条回答 默认 最新

  • duanjianfu1398 2014-04-14 22:16
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大