[英]PHP and HTTP Header Line Breaks: What character used to represent?
我遍历了一系列CURL返回的HTTP标头的每一行,试图检测何时结束以及下一个开始。 我知道http标头以空行结尾,但是用什么字符来表示php中的此换行符? 我已经尝试过\\n
但是似乎没有用。 我当然可能做错了。
用什么字符表示用于终止标题的换行符?
这是我现有的代码:
$redirect = '';
$regs = '';
foreach ($curl_response as $line)
{
if ($line != "\n")
{ # line is not a linebreak, so we're still processing a header block
if (preg_match("(HTTP/[0-9]\.[0-9] [0-9]{3} .*)",$line))
{ # line is the status code
# highlight the outputted line
$output .= "<b style='background: yellow;'>$line</b>";
}
elseif (preg_match("/^Location: (.*)$/m",$line,$regs))
{ # the line is a location header, so grab the location being redirected to
# highlight the outputted line
$output .= "<b style='background: purple; color: white;'>$line</b>";
$redirect = $regs[1];
}
else
{ # some other header, record to output
$output .= $line;
}
}
else
{ # we've reached a line break, so we're getting to a new block of redirects
$output .= "\nreached line break\n";
if ($redirect != '')
{ # if we recorded a redirect above, append it to output
$output .= "\n\nRedirecting to $redirect\n\n";
$redirect = '';
}
}
}
echo $output;
解决 -原来\\r
是我应该匹配的对象。 很奇怪。 不确定是否每个站点都会更改,或者是否设置了卷曲。 到目前为止,其\\r
上的所有网站我已经试过。
编辑2 :Doh。 我认为这是因为为了使标头成一行行,我在\\n
上进行了分解。 所以也许任何\\r\\n
现在只是\\r
...
$c = explode("\n",$content);
您还需要检查“ \\ r \\ n”和“ \\ r”,因为它们也是有效的终止空行。
当采用规范形式时,“文本”类型的媒体子类型使用CRLF作为文本换行符。 HTTP放宽了此要求,并允许在整个实体主体上一致执行时仅使用纯CR或LF表示换行符的文本媒体传输。 HTTP应用程序必须接受CRLF,裸CR和裸LF来表示通过HTTP接收的文本媒体中的换行符。
标头以双换行符结尾,中间没有空格(即,空行)。 换行符可以是“ \\ n”,“ \\ r \\ n”或只是“ \\ r”。 即使后者不常见,仍需要考虑。
也许您可以找到带有正则表达式的标头结尾,例如
list($headers) = preg_split('/(\r\n?|\n)(\r\n?|\n)/', $httpresponse);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.