【问题标题】:Finding out where curl was redirected找出 curl 被重定向的位置
【发布时间】:2010-12-13 20:58:57
【问题描述】:

我正在使用 curl 让 php 向某个网站发送一个 http 请求,并将 CURLOPT_FOLLOWLOCATION 设置为 1,以便它遵循重定向。那么,我怎样才能知道它最终被重定向到哪里?

【问题讨论】:

    标签: php http curl libcurl


    【解决方案1】:

    如果你不需要最终的身体,你可以这样做:

    设置CURLOPT_HEADERCURLOPT_NOBODY。应返回标头“Location”并将包含新的 url。然后根据需要使用新的 url 执行请求。

    【讨论】:

      【解决方案2】:

      你可以这样做:

      curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // returns the last effective URL
      

      【讨论】:

      • 不错。不知道这个。考虑到 curl 选项的数量,找到它们并不总是那么容易。谢谢。
      【解决方案3】:
      $ch = curl_init( "http://websitethatredirects.com" );
      $curlParams = array(
         CURLOPT_FOLLOWLOCATION => true,
      );
      curl_setopt_array( $ch, $curlParams );
      $ret = curl_exec( $ch );
      $info = curl_getinfo( $ch );
      print $info['url'];
      

      这将显示您最终被重定向到的 URL。

      【讨论】:

        【解决方案4】:

        测试这个sn-ps的代码。它对我来说很好:

        $urls = array(
            'http://www.apple.com/imac',
            'http://www.google.com/'
        );
        
        $ch = curl_init();
        
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        foreach($urls as $url) {
            curl_setopt($ch, CURLOPT_URL, $url);
            $out = curl_exec($ch);
        
            // line endings is the wonkiest piece of this whole thing
            $out = str_replace("\r", "", $out);
        
            // only look at the headers
            $headers_end = strpos($out, "\n\n");
            if( $headers_end !== false ) { 
                $out = substr($out, 0, $headers_end);
            }   
        
            $headers = explode("\n", $out);
            foreach($headers as $header) {
                if( substr($header, 0, 10) == "Location: " ) { 
                    $target = substr($header, 10);
        
                    echo "[$url] redirects to [$target]<br>";
                    continue 2;
                }   
            }   
        
            echo "[$url] does not redirect<br>";
        }
        

        【讨论】:

          猜你喜欢
          • 2011-04-01
          • 2011-03-13
          • 1970-01-01
          • 1970-01-01
          • 2010-12-10
          • 2023-04-03
          • 1970-01-01
          相关资源
          最近更新 更多