PHP cURL 可以在单个请求中检索响应标头和正文吗? [英] Can PHP cURL retrieve response headers AND body in a single request?

查看:23
本文介绍了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.

这篇关于PHP cURL 可以在单个请求中检索响应标头和正文吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆