我想正确理解 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/