Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curl, follow location but only get header of the new location?

Tags:

php

curl

I know that when I set CURLOPT_FOLLOWLOCATION to true, cURL will follow the Location header and redirect to new page. But is it possible only to get header of the new page without actually redirecting there? Or is it not possible?

like image 771
Richard Knop Avatar asked May 25 '11 18:05

Richard Knop


4 Answers

Appears to be a duplicate of PHP cURL: Get target of redirect, without following it

However, this can be done in 3 easy steps:

Step 1. Initialise curl

curl_init($ch); //initialise the curl handle
//COOKIESESSION is optional, use if you want to keep cookies in memory
curl_setopt($ch, CURLOPT_COOKIESESSION, true);

Step 2. Get the headers for $url

curl_setopt($ch, CURLOPT_URL, $url); //specify your URL
curl_setopt($ch, CURLOPT_HEADER, true); //include headers in http data
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); //don't follow redirects
$http_data = curl_exec($ch); //hit the $url
$curl_info = curl_getinfo($ch);
$headers = substr($http_data, 0, $curl_info["header_size"]); //split out header

Step 3. Parse the headers to get the new URL

preg_match("!\r\n(?:Location|URI): *(.*?) *\r\n!", $headers, $matches);
$url = $matches[1];

Once you have the new URL you can then repeat steps 2-3 as often as you like.

like image 187
Nathan Dunn Avatar answered Oct 27 '22 00:10

Nathan Dunn


No. You'd have to disable FOLLOWLOCATION, extract the redirect URL from the response, and then issue a new HEAD request with that URL.

like image 35
Marc B Avatar answered Oct 27 '22 00:10

Marc B


Set CURLOPT_FOLLOWLOCATION as false and CURLOPT_HEADER as true, and get the "Location" from the response header.

like image 21
fvox Avatar answered Oct 27 '22 01:10

fvox


Yes, you can set it to follow the redirect until you get the last location on the header response.

The function to get the last redirect:

function get_redirect_final_target($url)
{
    $ch = curl_init($url);        
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // set referer on redirect
    curl_setopt($ch,CURLOPT_HEADER,false); // if you want to print the header response change false to true
    $response = curl_exec($ch);
    $target = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    if ($target)
        return $target; // the location you want
    return false;
}
like image 21
Ahmed Soliman Avatar answered Oct 26 '22 23:10

Ahmed Soliman