views:

600

answers:

4

Hello

How to get the destination URL using cURL? when the http status code is 302?

       <?PHP
       $url = "http://www.ecs.soton.ac.uk/news/";
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL,$url);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       $html = curl_exec($ch);
       $status_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);           

       if($status_code=302 or $status_code=301){

         $url = "";
         // I want to to get the destination url   

       }
       curl_close($ch);
       ?>

Thanks

+2  A: 

You have to grab the Location header for the redirected URL.

raspi
A: 

The new destination for a 302 redirect ist located in the http header field "location". Example:

HTTP/1.1 302 Found
Date: Tue, 30 Jun 2002 1:20:30 GMT
Server: Apache
Location: http://www.foobar.com/foo/bar
Content-Type: text/html; charset=iso-8859-1

Just grep it with a regex.

To include all HTTP header information include it to the result with the curl option CURLOPT_HEADER. Set it with:

curl_setopt($c, CURLOPT_HEADER, true);

If you simply want curl to follow the redirection use CURLOPT_FOLLOWLOCATION:

curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);

Anyway, you shouldn't use the new URI because HTTP Statuscode 302 is only a temporary redirect.

echox
A: 

Here's a way to get all headers returned by a curl http request, as well as the status code and an array of header lines for each header.

$url = 'http://google.com';
$opts = array(CURLOPT_URL => $url,
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_HEADER => true,
              CURLOPT_FOLLOWLOCATION => true);

$ch = curl_init();
curl_setopt_array($ch, $opts);
$return = curl_exec($ch);
curl_close($ch);

$headers = http_response_headers($return);
foreach ($headers as $header) {
    $str = http_response_code($header);
    $hdr_arr = http_response_header_lines($header);
    if (isset($hdr_arr['Location'])) {
        $str .= ' - Location: ' . $hdr_arr['Location'];
    }
    echo $str . '<br />';
}

function http_response_headers($ret_str)
{
    $hdrs = array();
    $arr = explode("\r\n\r\n", $ret_str);
    foreach ($arr as $each) {
        if (substr($each, 0, 4) == 'HTTP') {
            $hdrs[] = $each;
        }
    }
    return $hdrs;
}

function http_response_header_lines($hdr_str)
{
    $lines = explode("\n", $hdr_str);
    $hdr_arr['status_line'] = trim(array_shift($lines));
    foreach ($lines as $line) {
        list($key, $val) = explode(':', $line, 2);
        $hdr_arr[trim($key)] = trim($val);
    }
    return $hdr_arr;
}

function http_response_code($str)
{
    return substr(trim(strstr($str, ' ')), 0, 3);
}
GZipp
A: 

use curl_getinfo($ch) and the first element ("url") would indicate the effective url.

Sabeen Malik