PHP cURL Get Redirect URL as Variable

Posted on September 6, 2017 at 10:55 pm

Get the redirect URL with cURL and PHP:

function get_redirect_url($url, $referer)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
    curl_setopt($ch, CURLOPT_REFERER, $referer);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $data = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    return $info['redirect_url'];
}

Example usage:

$url = "http://www.example.com/";
$referer = "http://www.referer.com/";
$redirect_url = get_redirect_url($url, $referer);
print_r($redirect_url);

Other Posts

Updated Posts