PHP獲得跳轉的真真實位址執行個體_PHP教程

來源:互聯網
上載者:User
現在有很多的短網址應用,點擊就跳轉到縮短之前的網址了,那今天我們就來看一下,PHP如何擷取短網址跳轉之前的網址,其實也很簡單,就是用php的get_headers 函數,

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

給出具體實現方法:

代碼如下 複製代碼

$header = get_headers($url, 1);
if (strpos($header[0], ’301′) || strpos($header[0], ’302′)) {
if (is_array($header['Location'])) {
return $header['Location'][count($header['Location'])-1];
} else {
return $header['Location'];
}
} else {
return $url;
}


執行個體二

代碼如下 複製代碼

//
echo get_redirect_url('http://www.111cN.nEt');
//輸出結果為:http://code.google.com/android/
function get_redirect_url($url){
$redirect_url = null;

$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'] = '/';

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

$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 (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]);

} else {
return false;
}

}

http://www.bkjia.com/PHPjc/631515.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/631515.htmlTechArticle現在有很多的短網址應用,點擊就跳轉到縮短之前的網址了,那今天我們就來看一下,PHP如何擷取短網址跳轉之前的網址,其實也很簡單,...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.