PHP cURL 可以在单个请求中检索响应标头和正文吗?
有没有办法使用 PHP 获取 cURL 请求的标头和正文?我发现这个选项:
Is there any way to get both headers and body for a cURL request using PHP? I found that this option:
curl_setopt($ch, CURLOPT_HEADER, true);
将返回 正文加上标题,但随后我需要解析它以获取正文.有没有办法以更有用(和安全)的方式获得两者?
is going to return the body plus headers, but then I need to parse it to get the body. Is there any way to get both in a more usable (and secure) way?
请注意,对于单个请求",我的意思是避免在 GET/POST 之前发出 HEAD 请求.
Note that for "single request" I mean avoiding issuing a HEAD request prior of GET/POST.
PHP 文档注释中发布了一个解决方案:http://www.php.net/manual/en/function.curl-exec.php#80442
One solution to this was posted in the PHP documentation comments: http://www.php.net/manual/en/function.curl-exec.php#80442
代码示例:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
// ...
$response = curl_exec($ch);
// Then, after your curl_exec call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
警告:如下面的评论所述,当与代理服务器一起使用或处理某些类型的重定向时,这可能不可靠.@Geoffrey 的回答可能会更可靠地处理这些问题.
Warning: As noted in the comments below, this may not be reliable when used with proxy servers or when handling certain types of redirects. @Geoffrey's answer may handle these more reliably.