How use CURLOPT_WRITEFUNCTION when download a file by CURL

后端 未结 4 1550
陌清茗
陌清茗 2021-01-20 04:10

My Class for download file direct from a link:

MyClass{

          function download($link){
                ......
                $ch = curl_init($link);
          


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-20 04:43

    It seems like cURL uses your function instead of writing to the request once CURLOPT_WRITEFUNCTION is specified.

    So the correct solution would be :

    MyClass{
    
          function download($link){
                ......
                $ch = curl_init($link);
                curl_setopt($ch, CURLOPT_FILE, $File->handle);
                curl_setopt($ch,CURLOPT_WRITEFUNCTION , array($this,'__writeFunction'));
                curl_exec($ch);
                curl_close($ch);
                $File->close();
                ......
    
            }
    
          function __writeFunction($curl, $data) {
                echo $data;
                return strlen($data);            
          } 
    }
    

    This can also handle binary files as well.

提交回复
热议问题