PHP cURL可以在单个请求中检索响应头和正文吗? [英] Can PHP cURL retrieve response headers AND body in a single request?
问题描述
有没有办法使用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之前发出HEAD请求/ POST。
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_VERBOSE, 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屋!