通过 CURL 下载文件时如何使用 CURLOPT_WRITEFUNCTION

meo*_*hia 3 php curl

我的类直接从链接下载文件:

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) {
                return strlen($data);            
          } 
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何在下载文件时使用 CRULOPT_WRITEFUNCTION。如果我删除行,则上面的代码:

curl_setopt($ch,CURLOPT_WRITEFUNCTION , array($this,'__writeFunction'));

然后它会运行良好,我可以下载该文件。但是如果我使用 CURL_WRITEFUNCTION 选项,我将无法下载文件。

Use*_*407 5

我知道这是一个老问题,但也许我的回答会对您或其他人有所帮助。尝试这个:

function get_write_function(){
    return function($curl, $data){
        return strlen($data);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道你到底想做什么,但是在 PHP 5.3 中,你可以用回调做很多事情。以这种方式生成函数的真正好处在于,通过 'use' 关键字传递的值随后会保留在函数中,有点像常量。

function get_write_function($var){
    $obj = $this;//access variables or functions within your class with the object variable
    return function($curl, $data) use ($var, $obj) {
        $len = strlen($data);
        //just an example - you can come up with something better than this:
        if ($len > $var){
            return -1;//abort the download
        } else {
            $obj->do_something();//call a class function
            return $len;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以将函数作为变量检索,如下所示:

function download($link){
    ......
    $var = 5000;
    $write_function = $this->get_write_function($var);
    $ch = curl_init($link);
    curl_setopt($ch, CURLOPT_FILE, $File->handle);
    curl_setopt($ch, CURLOPT_WRITEFUNCTION , $write_function);
    curl_exec($ch);
    curl_close($ch);
    $File->close();
    ......

}
Run Code Online (Sandbox Code Playgroud)

那只是一个例子。你可以在这里看到我是如何使用它的:Parallel cURL Request with WRITEFUNCTION Callback。我实际上并没有测试所有这些代码,所以可能会有小错误。如果您有问题,请告诉我,我会解决它。