且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP cURL可以在单个请求中检索响应头和正文吗?

更新时间:2023-02-24 16:09:54

在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.