In my CURL CURLOPT_PROGRESSFUNCTION callback, dlto

2019-07-04 16:50发布

I've got a CURL progress callback working via the CURLOPT_PROGRESSFUNCTION option which is successfully calling my member function in PHP. The dlnow variable is returning a correct received value, but dltotal always returns 0. What am I missing here?

class MyClass {

    function getFile(){

    ...

      $fp = fopen ($file, 'w+');
      $curl = curl_init();
      curl_setopt($curl,CURLOPT_URL,$signed['signed_url']);
      curl_setopt($curl, CURLOPT_TIMEOUT, 1000);
      curl_setopt($curl, CURLOPT_FILE, $fp); // write curl response to file
      curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
      curl_setopt($curl, CURLOPT_NOPROGRESS, 0);
      curl_setopt($curl, CURLOPT_PROGRESSFUNCTION, array($this, 'curl_progress_callback'));

    }

    function curl_progress_callback($dltotal, $dlnow, $ultotal, $ulnow){
        echo $dltotal; //Reports correct value
        echo $dlnow;   //Always returns 0
    }

}

EDIT: This post has been updated with info from @Sabuj Hassan. Originally I thought I was receiving a correct dltotal but an incorrect dlnow but I had an additional unnecessary argument in my callback function.

3条回答
三岁会撩人
2楼-- · 2019-07-04 17:32

NOTE: for libcurl older than 7.32.0

the callback function need has the following format

curl_progress_callback($resource,$dltotal, $dlnow, $ultotal, $ulnow)

where as newer curl binary does not require the resource

curl_progress_callback($dltotal, $dlnow, $ultotal, $ulnow)

check your curl version version with

curl -V
查看更多
甜甜的少女心
3楼-- · 2019-07-04 17:39

The problem seems to be that the website I'm requesting isn't sending an http content-length so dltotal is always empty. Thanks to @Subuj Hassan for correcting my error in my curl_progress_callback which had one too many values and made me originally think that the issue was with the dlnow value.

查看更多
趁早两清
4楼-- · 2019-07-04 17:56

Try this with removing the class:

curl_setopt($curl, CURLOPT_PROGRESSFUNCTION, 'curl_progress_callback');

Then remove the first parameter from the callback.

function curl_progress_callback($dltotal, $dlnow, $ultotal, $ulnow){
   ...
}

UPDATE: A working code: Try to run it from your end.

function getFile(){
  $fp = fopen ("output.html", 'w+');
  $curl = curl_init();
  curl_setopt($curl,CURLOPT_URL,'http://www.mashable.com/');
  curl_setopt($curl, CURLOPT_TIMEOUT, 1000);
  curl_setopt($curl, CURLOPT_FILE, $fp);
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($curl, CURLOPT_NOPROGRESS, 0);
  curl_setopt($curl, CURLOPT_PROGRESSFUNCTION, 'curl_progress_callback');

  $result = curl_exec($curl);
  fclose($fp);

}

function curl_progress_callback($dltotal, $dlnow, $ultotal, $ulnow){
    echo "$dltotal\n";
    echo "$dlnow\n";
}

getFile();
查看更多
登录 后发表回答