How to get headers from the last redirect with PHP curl functions?

If I execute a cURL request that is configured to re-redirect and return headers, it returns headers for ALL redirects.

I only need the last returned header (and the content body). How do I achieve this?

+3
source share
4 answers

A search in the string "HTTP / 1.1 200 OK" at the beginning of the line is where your last request will begin. All others will pass other HTTP return codes.

+2
source

Here's another way:

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

Of course, you will need additional error checking, for example, for a timeout, etc.

+2
source
  • curl_getinfo

  • Get the part between the last \r\n\r\n(but until the end of the heading) and the end of the heading as the last heading

// 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);

Of course, if you have PHP <5.3, you must expand the elvis operator into the if / else construct.

0
source

Late answer, but perhaps a simpler way:

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

Source: https://habr.com/ru/post/1756370/


All Articles