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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)