获取HTTP协议内容
将返回
array ( 'header' => array(), 'code' => 200, 'proto' => 'HTTP/1.1', 'body' => '', )
array Module_Storage_Driver_Swift::read( fsockopen $fp )
参数列表
参数 类型 描述 默认值 $fp
fsockopen
$fp
array
protected function read($fp)
{
$rs = array
(
'code' => 0,
'header' => array(),
'body' => '',
);
# 读取第一行
$head_line = fgets($fp);
if (preg_match('#^(HTTP/[0-9\.]+) ([0-9]+) ([a-z0-9 ]+)?$#i', trim($head_line), $m))
{
$rs['proto'] = $m[1];
$rs['code'] = (int)$m[2];
}
else
{
throw new Exception(__('Swift get data error.Data: :data', array(':data'=>$head_line)));
}
# 是否分片读取
$transfer_encoding = false;
# 内容长度
$content_length = 0;
# 是否读取body部分
$read_body = false;
$switch = false;
while (true)
{
if ($switch)
{
# 退出
break;
}
if ($read_body)
{
if ($transfer_encoding)
{
$chunk = trim(fgets($fp));
$chunk_length = hexdec($chunk);
if ($chunk_length>0)
{
$rs['body'] .= fread($fp, $chunk_length);
}
else
{
fread($fp, 2); //读取最后的结束符 \r\n
$switch = true;
}
}
else
{
if ($content_length>0)
{
$rs['body'] = fread($fp, $content_length);
}
$switch = true;
}
}
else
{
$tmp = fgets($fp);
if ($tmp=="\r\n")
{
$read_body = true;
}
else
{
list($k, $v) = explode(':', $tmp, 2);
$k = trim($k);
$v = trim($v);
$rs['header'][$k] = $v;
if ($k=='Content-Length')
{
$content_length = $v;
}
else if ($k=='Transfer-Encoding')
{
# 分片获取
$transfer_encoding = true;
}
}
}
}
return $rs;
}