2010-07-24 40 views

回答

2

在行的开头搜索“HTTP/1.1 200 OK”的输出 - 这是您最后一次请求开始的位置。所有其他人将提供其他HTTP返回码。

+0

啊。好想法。谢谢! – 2010-07-24 21:22:06

+0

有一件事 - HTTP 1.0呢? 200后的标准信息是'OK'吗? – 2010-07-24 21:24:46

+1

我会使用类似preg_match('/^HTTP 1 \ [01] 200 /'...以确保在HTTP 1.0上的优点.OK是事实上的标准,但RFC仅指定结果number(200)。 – m1tk4 2010-07-24 21:33:58

2

这里的另一种方式:

$url = 'http://google.com'; 

$opts = array(CURLOPT_RETURNTRANSFER => true, 
       CURLOPT_FOLLOWLOCATION => true, 
       CURLOPT_HEADER   => true); 
$ch = curl_init($url); 
curl_setopt_array($ch, $opts); 
$response  = curl_exec($ch); 
$redirect_count = curl_getinfo($ch, CURLINFO_REDIRECT_COUNT); 
$status   = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
$response  = explode("\r\n\r\n", $response, $redirect_count + 2); 
$last_header = $response[$redirect_count]; 
if ($status == '200') { 
    $body = end($response); 
} else { 
    $body = ''; 
} 
curl_close($ch); 

echo '<pre>'; 
echo 'Redirects: ' . $redirect_count . '<br />'; 
echo 'Status: ' . $status . '<br />'; 
echo 'Last response header:<br />' . $last_header . '<br />'; 
echo 'Response body:<br />' . htmlspecialchars($body) . '<br />'; 
echo '</pre>'; 

当然,你需要更多的错误检查,如超时等

+1

如果其中一个重定向响应主体包含额外的\ r \ n \ r \ n,会发生什么? – m1tk4 2010-07-25 16:38:07

+0

我最终做的只是在301和302响应中循环重定向。 – 2010-07-25 16:54:16

+1

@ m1tkr - 这就是为什么explode()调用包含限制参数($ redirect_count + 2)。 – GZipp 2010-07-25 17:04:36

0
  1. 执行您的要求

  2. 拿表头长度从curl_getinfo s返回值

  3. 检索之间的部分的最后\r\n\r\n(但在头年底前)和标题的末尾作为最后一个头

// Step 1: Execute 
$fullResponse = curl_exec($ch); 

// Step 2: Take the header length 
$headerLength = curl_getinfo($ch, CURLINFO_HEADER_SIZE); 

// Step 3: Get the last header 
$header = substr($fullResponse, 0, $headerLength - 4); 
$lastHeader = substr($header, (strrpos($header, "\r\n\r\n") ?: -4) + 4); 

当然,如果你有PHP < 5.3你必须展开elvis operator到一个if/else构造。

0

迟到的答案,但也许更简单的方法来;

$result = explode("\r\n\r\n", $result); 

// drop redirect etc. headers 
while (count($result) > 2) { 
    array_shift($result); 
} 

// split headers/body parts 
@ list($headers, $body) = $result;