如何在跟踪链接的所有重定向后获得最终重定向的URL?

时间:2014-01-29 11:22:26

标签: php curl

我想在php中进行所有重定向后获得最终重定向的url。我使用了很多从网上搜索过的函数和代码,但没有人对某些跟踪网址是正确的。

这是我的网址:http://performance.ikoo.com/geo_tracking_redirect.html?a=CD441&program_id=1304274

它最终重定向到:https://www.shopandship.com/my-shopandship/profile.aspx

如何获取此类网址的最终重定向网址。 请帮忙。

3 个答案:

答案 0 :(得分:2)

试试这个。

        <?php


    function getLastEffectiveUrl($url)
    {
        // initialize cURL
        $curl = curl_init($url);
        curl_setopt_array($curl, array(
            CURLOPT_RETURNTRANSFER  => true,
            CURLOPT_FOLLOWLOCATION  => true,
        ));

        // execute the request
        $result = curl_exec($curl);

        // extract the target url
        $redirectUrl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
        curl_close($curl);

        return $redirectUrl;
    }

    $url="http://performance.ikoo.com/geo_tracking_redirect.html?a=CD441&program_id=1304274";

    $lastEffectiveUrl = getLastEffectiveUrl($url);


    if($lastEffectiveUrl==$url)
    {
        $url_data=file_get_contents($url);

        $domHtmlStr = new DOMDocument();
        $domHtmlStr->loadHTML($url_data);
        $metaTag = $domHtmlStr->getElementsByTagName('meta');

        foreach($metaTag as $metaTagVal)
        {
          if($metaTagVal->getAttribute("http-equiv")=="refresh")
          {
            $metaContent = $metaTagVal->getAttribute("content");
            break;
          }
        }

        if($metaContent!="")
        {
         $metaContentSplit=explode("URL=",$metaContent);
         $lastEffectiveUrl1 = getLastEffectiveUrl(trim($metaContentSplit[1]));
         echo "Final URL : ".$lastEffectiveUrl1;
        }

    }

?>

来源:http://codeaid.net/php/get-the-last-effective-url-from-a-series-of-redirects-for-the-given-url

注意:http://performance.ikoo.com/geo_tracking_redirect.html?a=CD441&program_id=1304274未加载!

答案 1 :(得分:0)

你可以试试this url ..

的代码

返回重定向的网址以跟踪网址..

$url = "http://www.awin1.com/awclick.php?mid=5477&id=129196";    
stream_context_set_default(array('http' => array('method' => 'HEAD')));
print_r(get_headers($url, 0));
$larr = get_headers($url, 1)["Location"];

$loc = is_array($larr) ? array_pop($larr):$larr;
echo $loc."</pre>";
$domain = parse_url($loc, PHP_URL_HOST);
print_r($domain);

答案 2 :(得分:0)

Goutte可以为你做到这一点。 https://github.com/FriendsOfPHP/Goutte

它将遵循HTTP 3xx重定向以及<meta http-equiv="refresh">标记。

示例代码:

$client= new \Goutte\Client();
$url="http://www.awin1.com/awclick.php?mid=5477&id=129196";
echo $client->request("GET",$url)->getUri();
相关问题