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

标签 php curl

My Class 直接从链接下载文件:

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);            
          } 
}

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

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

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

最佳答案

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

function get_write_function(){
    return function($curl, $data){
        return strlen($data);
    }
}

我不知道你到底想做什么,但是使用 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;
        }
    }
}

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

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();
    ......

}

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

关于php - 通过 CURL 下载文件时如何使用 CURLOPT_WRITEFUNCTION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5359787/

相关文章:

php - 预期响应代码 220 但得到代码 "500",并显示消息“500 Unknown command Laravel

PHP PCRE 在测试和托管服务器上的差异

php - 如何让用户保持登录状态,直到他们注销或关闭浏览器

curl - 使用 CouchDB 进行基本身份验证

amazon-web-services - 使用 Curl(通过低级 API)将记录插入亚马逊的 DynamoDB

php - 如何在 php-curl 中使用 CURLOPT_LOGIN_OPTIONS?

php - WP 字幕 - 格式

php - "Delivered Message to APNS"但在使用 ios13 (PHP) 的生产环境中未显示通知

curl - 使用 cURL 对 SharePoint Online 进行身份验证(使用 ADFS 2.1 作为 IP-STS)

json - 从控制台使用 json 和 curl 的工具