php - 帮助我理解 CURLOPT_READFUNCTION

标签 php curl libcurl

我想正确理解 CURLOPT_READFUNCTION。

我正在查看 Rackspace coudfiles php 代码(REST API)。

它有下面一行。

curl_setopt($ch, CURLOPT_READFUNCTION, array(&$this, '_read_cb'));

查看此函数的定义:

private function _read_cb($ch, $fd, $length)
{
    $data = fread($fd, $length);
    $len = strlen($data);
    if (isset($this->_user_write_progress_callback_func)) {
        call_user_func($this->_user_write_progress_callback_func, $len);
    }
    return $data;
}

你能帮我理解传递给 $fd 和 $length 的值是什么吗?

我想具体指定 $length 值,以分块发送文件。

提前致谢。

最佳答案

我知道这有点死机 - 但其他人可能想知道它是如何工作的。

这是一个典型的 curl 文件 put block 的样子:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ret['Location']);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_READFUNCTION, 'curlPutThrottle');
curl_setopt($ch, CURLOPT_INFILE, $fh);
curl_setopt($ch, CURLOPT_INFILESIZE, $size);

$ret = curl_exec($ch);

并且读取功能看起来像这样(这个限制用户定义的 $goal 速度并提供 CLI 显示反馈)

function curlPutThrottle($ch, $fh, $length = false)
{
    global $size;
    global $current;
    global $throttle;
    global $start;

    /** Set your max upload speed - here 30mB / minute **/
    $goal = (300*1024*1024)/(60*10);

    if (!$length)
    {
        $length = 1024 * 1024;
    }

    if (!is_resource($fh))
    {
        return 0;
    }

    $current += $length;

    if ($current > $throttle) /** Every meg uploaded we update the display and throttle a bit to reach target speed **/
    {
        $pct = round($current/$size*100);
        $disp =  "Uploading (".$pct."%)  -  ".number_format($current, 0).'/'.number_format($size, 0);
        echo "\r     ".$disp.str_repeat(" ", strlen($disp));
        $throttle += 1024*1024;

        $elapsed = time() - $start;
        $expectedUpload = $goal * $elapsed;

        if ($current > $expectedUpload)
        {
            $sleep = ($current - $expectedUpload) / $goal;
            $sleep = round($sleep);

            for ($i = 1; $i <= $sleep; $i++)
            {
                echo "\r Throttling for ".($sleep - $i + 1)." Seconds   - ".$disp;
                sleep(1);
            }
            echo "\r     ".$disp.str_repeat(" ", strlen($disp));
        }
    }

    if ($current > $size)
    {
        echo "\n";
    }

    return fread($fh, $length);
}

地点:

  • $ch 是调用 ReadFunction 的 cURL 资源
  • $fh 是来自 CURLOPT_INFILE 的文件句柄
  • $length 是它期望返回的数据量。

它从长度为 $length 的文件返回数据,如果 EOF 则返回 ''。

关于php - 帮助我理解 CURLOPT_READFUNCTION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5619429/

相关文章:

php - jQuery $.post 返回的数据

php - 用户下载后删除文件

php - 使用curl从网站发布到Facebook页面

json - 如何使用命令行计算 JSON 对象中的项目?

c++ - 添加到 char 数组不起作用

php - SQL-在子句中使用LIKE时根据第一优先级对数据进行排序

java - HttpUrlConnection 身份验证不起作用

c++ - curl 请求的用户输入

c - libcurl (linux, C) - 是否有一种内置的方法来发布/放置 gzip 压缩请求?

php - 如何在多维数组上使用 array_multisort()