代码之家  ›  专栏  ›  技术社区  ›  Nathan Osman

如何使用PHP的curl函数从上一次重定向中获取头文件?

  •  4
  • Nathan Osman  · 技术社区  · 14 年前

    如果我执行一个设置为遵循重定向并返回头的curl请求,它将返回所有重定向的头。

    我只希望返回最后一个标题(和内容正文)。我怎样才能做到?

    4 回复  |  直到 7 年前
        1
  •  2
  •   m1tk4    14 年前

    在行的开头搜索“http/1.1200 OK”的输出-这是最后一个请求的开始位置。所有其他的将给出其他HTTP返回代码。

        2
  •  3
  •   GZipp    14 年前

    另一种方法是:

    $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>';
    

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

        3
  •  0
  •   Matteo B.    8 年前
    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构造。

        4
  •  0
  •   Kerem    7 年前

    回答晚了,但也许更简单的方法;

    $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;