Doubidou
Doubidou

Reputation: 1791

Get download size on-the-fly with cURL

I wrote a PHP script that get a distant file and give it to a client, with cURL.

It works like a proxy...

The call :

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

Now, I would like to know how many bytes the client has downloaded (in live, even if the download is stopped)

I think I could write something on myProgressFunc() to get this, but I don't know how :/

Does anybody know how to achieve this ?

Thanks !

EDIT : Hmm... myProgressFunc() returns strlen(), so it's the size in bytes of what it's downloaded, right ?

Upvotes: 0

Views: 595

Answers (1)

ben_makes_stuff
ben_makes_stuff

Reputation: 508

Use curl_setopt($curl, CURLOPT_PROGRESSFUNCTION, "myProgressFunc") instead of WRITEFUNCTION. See here: cURL download progress in PHP

Upvotes: 1

Related Questions