我使用此代码返回使用php curl下载数据的百分比
<?php
$url = 'http://exemple.com/';
$path = 'index.html';
$fp = fopen($path, 'w');
$ch=curl_init() or die("ERROR|<b>Error:</b> cURL Error");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_FILE, $fp);
//####################################################//
// This is required to curl give us some progress
// if this is not set to false the progress function never
// gets called
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
// Set up the callback
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'callback');
// Big buffer less progress info/callbacks
// Small buffer more progress info/callbacks
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
//####################################################//
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
进度回调函数,
function callback($download_size, $downloaded, $upload_size, $uploaded)
{
$percent = $downloaded/$download_size;
// Do something with $percent
echo sprintf('%.2f', $percent*100);
echo '%<br/>';
echo str_repeat(' ', 8192);
flush();
}
我认为,我在进程回调函数中出错了,我尝试获取接收位的方法,但仍然无法使用此方法。
bps = time elapsed / size received;
Remaining Time = (Total size - size received) * bps
但我仍然在结果中得到这个:
0.00%
0.00%
0.00%
0.00%
0.00%
0.00%
0.00%
0.00%
0.00%
0.00%
0.00%
为什么这不起作用,还有其他方法可以解决这个问题吗?
答案 0 :(得分:0)
function handle() {
$this->db->prep("
update
`links`
set
`status`='toDownload',
`processStartDate` = now()
where
`id` = ?
limit
1
;
")->bind([$this->link->id]);
$ch = curl_init();
$fp = fopen(__DIR__ . "/test.data", "w+");
curl_setopt($ch, CURLOPT_URL, $this->link->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
$t = new DateTime();
$db = $this->db;
$linkId = $this->link->id;
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function ($resource,$download_size, $downloaded, $upload_size, $uploaded) use ($t, $db, $linkId) {
if ($download_size > 0 && ($t < new DateTime())) {
$p = round(($downloaded / $download_size) * 100, 2);
echo "download_size: $download_size, downloaded: $downloaded, p: $p%, t: ".$t->format("Y-m-d H:i:s")."\r\n";
$t->modify("+1 second");
$db->prep("update links set `progress` =? where `id`=? limit 1")->bind([
$p,
$linkId
]);
}
});
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $this->agent);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$this->db->prep("update `links` set `progress`='100', `status`='done' where `id` = ? limit 1")->bind([
$this->link->id
]);
}