duanche9384 2016-01-27 17:35
浏览 74
已采纳

使用Curl PHP获得最终重定向

I have to get the final redirect url from the this: https://web.archive.org/web/20070701005218/http://www.maladnews.com/ which actually redirects to this: https://web.archive.org/web/20080109064420/http://www.maladnews.com/Site%203/Malad%20City%20&%20Oneida%20County%20News/Malad%20City%20&%20Oneida%20County%20News.html

I tried the answers from other stackoverflow answers which works for other websites but not for the above link.

I've tried to extract regular location header:

if(preg_match('#Location: (.*)#', $html, $m))
 $l = trim($m[1]);

and also checked the javascript way:

preg_match("/window\.location\.replace\('(.*?)'\)/", $html, $m) ? $m[1] : null;

Please help!

  • 写回答

1条回答 默认 最新

  • duanputian5341 2016-01-27 19:34
    关注

    Use curl_getinfo() with CURLINFO_REDIRECT_URL or CURLINFO_EFFECTIVE_URL depending on your use case.

    CURLINFO_REDIRECT_URL - With the CURLOPT_FOLLOWLOCATION option disabled: redirect URL found in the last transaction, that should be requested manually next. With the CURLOPT_FOLLOWLOCATION option enabled: this is empty. The redirect URL in this case is available in CURLINFO_EFFECTIVE_URL

    -- http://php.net/manual/en/function.curl-getinfo.php

    Example:

    <?php
    $url = 'https://google.com/';
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    
    $html = curl_exec($ch);
    
    $redirectedUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    
    curl_close($ch);
    
    echo "Original URL:   " . $url . "
    ";
    echo "Redirected URL: " . $redirectedUrl . "
    ";
    

    When I run this code, the output is:

    Original URL:   https://google.com/
    Redirected URL: https://www.google.com/
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题