Zhi Wang
Zhi Wang

Reputation: 1168

'redirect_url' not returned in curl_getinfo

I wrote code similar to following to get a redirect url, this code works fine on my local machine, however on my hosting server, the 'redirect_url' is not supported by the curl version on the host server, do you know how can I solve this? i.e., how can I achieve the same goal (issue a http request with referer and then get the redirect url without the help of 'redirect_url'), thanks!

<?php
$ch = curl_init(); 

$referer= "xxx";
$url = "xxx";

curl_setopt($ch, CURLOPT_REFERER, $referer);
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

$result = curl_exec($ch);

$info = curl_getinfo($ch);

$redirect_url = $info['redirect_url'];

curl_close($ch);
?>

Upvotes: 3

Views: 4288

Answers (5)

GwenM
GwenM

Reputation: 1335

PHP 5.3.7 Introduced CURLINFO_REDIRECT_URL. See that you don't have an older version

Upvotes: 2

Atef
Atef

Reputation: 633

The solution I did is allowing the plugin to return headers and extract the location parameters

curl_setopt($ch, CURLOPT_HEADER, 1);
$exec=curl_exec($ch);
$x=curl_error($ch);
$cuinfo = curl_getinfo($ch);

if( $cuinfo['http_code'] == 302 && ! isset($cuinfo['redirect_url']) ){

    if(stristr($exec, 'Location:')){


        preg_match( '{Location:(.*)}' , $exec, $loc_matches);
        $redirect_url = trim($loc_matches[1]);

        if(trim($redirect_url) !=  ''){
            $cuinfo['redirect_url'] = $redirect_url;
        }


    }

}

Upvotes: 3

Jos&#233; Carlos PHP
Jos&#233; Carlos PHP

Reputation: 1492

If I use curl without FOLLOWLOCATION, I get a redirect_url element in curl info. This simplify the task for "manual" redirection, but it seems it depends on curl version.

The alternative is to analyze response header and get redirect url from there. This can help: http://slopjong.de/2012/03/31/curl-follow-locations-with-safe_mode-enabled-or-open_basedir-set/

Upvotes: 0

Drahcir
Drahcir

Reputation: 11972

According to the documentation, curl_getinfo does not return an array key named "redirect_url". Perhaps you need CURLINFO_EFFECTIVE_URL, or the array key "url":

  • $redirect_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

    Or

  • $redirect_url = $info["url"];

CURLINFO_EFFECTIVE_URL is the last effective url, so if a request was redirected then the final url will be here.


Also, note that if you want curl to follow the redirect then you will need to set CURLOPT_FOLLOWLOCATION before making the request:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

Upvotes: 4

Get Off My Lawn
Get Off My Lawn

Reputation: 36311

CURL doesn't have redirect_url, instead it uses url, so replace this:

$redirect_url = $info['redirect_url'];

with this:

$redirect_url = $info['url'];

Upvotes: 0

Related Questions