Menu
Woocommerce Menu

解析php 版获取重定向后的地址(代码)

0 Comment

    $url_parts = @parse_url($url);
    if (!$url_parts) return false;
    if (!isset($url_parts[‘host’])) return false; //can’t process
relative URLs
    if (!isset($url_parts[‘path’])) $url_parts[‘path’] = ‘/’;

 /**
  * get_show_pic
  * 取最终要显示的图片地址
  *
  * @param string $url
  * @return  string
  */
 function get_show_pic($url,$noimg
=’noimg.gif’,$newimg=”
     $obj = new RedirectUrl($url);

取得Response Headers,之后慢慢分析就行了。

         $sock = fsockopen($url_parts[‘host’],
(isset($url_parts[‘port’]) ? (int)$url_parts[‘port’] : 80),
$errno, $errstr, 30);
         if (!$sock) return false;

实例二

         if (preg_match(‘/^Location: (.+?)$/m’, $response,
$matches)){
             return trim($matches[1]);
         } else {
             return false;
         }
     }

    if
(preg_match(‘/^Location:
(.+?)$/m’, $response, $matches)){
        if (
substr($matches[1], 0, 1) ==
“/” )
            return $url_parts[‘scheme’] . “://” .
$url_parts[‘host’] . trim($matches[1]);
        else
            return trim($matches[1]);

         $request = “HEAD ” . $url_parts[‘path’] .
(isset($url_parts[‘query’]) ?’?’.$url_parts[‘query’] : ”) . ”
HTTP/1.1\r\n”;
         $request .= ‘Host: ‘ . $url_parts[‘host’] . “\r\n”;
         $request .= “Connection: Close\r\n\r\n”;
         fwrite($sock, $request);
         $response = ”;
         while(!feof($sock)) $response .= fread($sock, 8192);
         fclose($sock);

 代码如下

     /**
      * get_final_url()
      * 取实际地址
      *
      * @param string $url
      * @return string
      */
     function get_final_url(){
         $redirects = $this->get_all_redirects($this->url);

}

     $realurl = $obj->get_final_url();

    $request = “HEAD ” .
$url_parts[‘path’] . (isset($url_parts[‘query’]) ?
‘?’.$url_parts[‘query’] : ”) . ” HTTP/1.1rn”;
    $request .= ‘Host: ‘ . $url_parts[‘host’] . “rn”;
    $request .= “Connection: Closernrn”;
    fwrite($sock, $request);
    $response = ”;
    while(!feof($sock)) $response .= fread($sock, 8192);
    fclose($sock);

         if (count($redirects)>0){
             return array_pop($redirects);
         } else {
             return $this->url;
         }
     }
 }

标签:

发表评论

电子邮件地址不会被公开。 必填项已用*标注

相关文章

网站地图xml地图