代码之家  ›  专栏  ›  技术社区  ›  Keyslinger

使用PHP捕获重定向URL

  •  1
  • Keyslinger  · 技术社区  · 15 年前

    我想使用php获取以下地址重定向到的页面的URL:

    http://peacecorpsjournals.com/journal/6731

    脚本应返回上面的URL重定向到的以下URL:

    http://ghanakimsuri.blogspot.com/

    4 回复  |  直到 14 年前
        1
  •  1
  •   Chris    15 年前

    一种方法(很多方法)是用 fopen 然后使用 stream_get_meta_data 抓住收割台。这是我从前写的一段话中抓到的一个小片段:

      $fh = fopen($uri, 'r');
      $details = stream_get_meta_data($fh);
    
      foreach ($details['wrapper_data'] as $line) {
       if (preg_match('/^Location: (.*?)$/i', $line, $m)) {
         // There was a redirect to $m[1]
       }
      }

    注意,您可以有多个重定向,它们可以是相对的也可以是绝对的。

        2
  •  1
  •   Oren Hizkiya    15 年前

    你可以用卷发来做这个。

    <?php
    
    function get_web_page( $url ) 
    { 
        $options = array( 
            CURLOPT_RETURNTRANSFER => true,     // return web page 
            CURLOPT_HEADER         => true,    // return headers 
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects 
            CURLOPT_ENCODING       => "",       // handle all encodings 
            CURLOPT_USERAGENT      => "spider", // who am i 
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect 
            CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect 
            CURLOPT_TIMEOUT        => 120,      // timeout on response 
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects 
        ); 
    
        $ch      = curl_init( $url ); 
        curl_setopt_array( $ch, $options ); 
        $content = curl_exec( $ch ); 
        $err     = curl_errno( $ch ); 
        $errmsg  = curl_error( $ch ); 
        $header  = curl_getinfo( $ch ); 
        curl_close( $ch ); 
    
        //$header['errno']   = $err; 
       // $header['errmsg']  = $errmsg; 
        //$header['content'] = $content; 
        print($header[0]); 
        return $header; 
    }  
    $thisurl = "http://www.example.com/redirectfrom";
    $myUrlInfo = get_web_page( $thisurl ); 
    echo $myUrlInfo["url"];
    
    ?>
    

    此处找到的代码: http://forums.devshed.com/php-development-5/curl-get-final-url-after-inital-url-redirects-544144.html

        3
  •  0
  •   buley    15 年前

    我找到了 this resource 是最完整、最深思熟虑的方法和解释。这段代码不是最短的截图,但最终你可以用如下几行跟踪多个重定向:

    $result = get_all_redirects('http://bit.ly/abc123');
    print_r($result);
    
        4
  •  0
  •   Cat    14 年前

    我发现您可以简单地使用以下代码在一个简单的重定向上获取重定向URL。这对递归重定向不起作用。

    $headers = get_headers("https://graph.facebook.com/me/picture?access_token=__token__", 1);
    $image_url = $headers['Location'];
    

    **上面的示例是从图形API调用中捕获Facebook配置文件图像URL,该调用与HTTP 302头一起发出。