取得301转向后的地址

PHP CODE:

<?php
function get_301($url){
    while (true){
        $matches = parse_url($url);
        if ( ! @$matches['host']){
            throw new Exception('url wrong!');
        }
        $host = @$matches['host'];
        $matches['query']=isset($matches['query'])?$matches['query']:null;
        $path = @$matches['path'] ? @$matches['path'].(@$matches['query'] ? '?'.@$matches['query'] : '') : '/';
        $port = !empty($matches['port']) ? $matches['port'] : 80;
        $out = "GET $path HTTP/1.1\r\n";
        $out .= "Host: $host\r\n";
        $out .= "User-Agent: Mozilla/5.0 (Android; Tablet; rv:14.0) Gecko/14.0 Firefox/14.0\r\n";//return mp4
        $out .= "Referer: http://$host\r\n";
        $out .= "Connection: Close\r\n\r\n";
        $timeout=5;
        $fp = fsockopen( $host, $port, $errno, $errstr,$timeout);
        stream_set_blocking($fp, TRUE);
        stream_set_timeout($fp, $timeout);
        @fwrite($fp, $out);
        $status = stream_get_meta_data($fp);
        if($status['timed_out']) {
            @fclose($fp);
            throw new Exception('time out!');
        }
        $ru=false;
        $status=true;
        while ( ! feof($fp)) {
            if(($header = fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
                break 2;
            }
            $header=trim($header);
            if (preg_match('/^\s*Location:\s*(.*)$/si', $header,$match)){
                @fclose($fp);
                $url=trim($match[1]);
                if (!preg_match('/^http:\/\//si',$url)){
                    $url=$matches['scheme']."://".$matches['host'].$url;
                }
                continue 2;
            }
            if($status&&preg_match_all("/http\/[0-9]\.[0-9]\s*(\d{3}).*/i",$header,$match,2)){
                if(trim($match[0][1])==200){
                    @fclose($fp);
                    break 2;
                }
            }
        }
        @fclose($fp);
    }
    return $url;
}
echo get_301('http://once.unicornmedia.com/now/od/auto/dd04fb63-53af-417a-be12-2abf285306e6/8b7e3c6e-8700-4656-b289-5af7250ef118/0-b0u7nb80/content.once');
exit;

 

posted @ 2013-04-01 16:17  liushan  阅读(203)  评论(0编辑  收藏  举报