使用cURL实时获取下载大小


Get download size on-the-fly with cURL

我编写了一个PHP脚本,使用cURL获取远程文件并将其提供给客户端。

它就像一个代理…

调用:

<?php
[...]
    public function streamContent($url)
    {
        $curl = curl_init();
        curl_setopt($curl,  CURLOPT_URL, $url);
        curl_setopt($curl,  CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl,  CURLOPT_FILETIME, true);
        if($this->cookie) {
            curl_setopt($curl,    CURLOPT_COOKIEFILE,     $this->cookie);
            curl_setopt($curl,    CURLOPT_COOKIEJAR,      $this->cookie);
        }
        if($this->follow) {
            curl_setopt($curl,    CURLOPT_FOLLOWLOCATION, 1);
        }
        curl_setopt($curl,  CURLOPT_HEADERFUNCTION, array($this, "streamHeader"));
        curl_setopt($curl,  CURLOPT_WRITEFUNCTION,  array($this, "myProgressFunc"));
        $data = curl_exec($curl);
        curl_close($curl);
    }
    private function streamHeader($curl,$string)
    {
        $stringTrim = trim($string);
        if(!empty ($stringTrim)) {
            if(!preg_match('~chunk~i', $stringTrim)) header($stringTrim);
        }
        return strlen($string);
    }
    private function myProgressFunc($curl, $str)
    { 
        echo $str;
        return strlen($str);
    }
[...]
$object->streamContent('http://url_to_distant_file');
?>

现在,我想知道客户端下载了多少字节(在活动中,即使下载已停止)

我想我可以在myProgressFunc()上写点什么来得到这个,但我不知道怎么做:/

有人知道如何实现这个吗?

谢谢!

编辑:嗯…myProgressFunc()返回strlen()所以它是以字节为单位的下载文件的大小,对吗?

curl_setopt($curl, CURLOPT_PROGRESSFUNCTION, "myProgressFunc")代替WRITEFUNCTION。PHP中的cURL下载进度