php 擷取301跳轉後真實的url

來源:互聯網
上載者:User

標籤:http   java   os   io   ar   問題   cti   伺服器   

在php採集中經常遇到有URL 301重新導向的情況,如果出現了這樣的情況,有可能出現造成未知的結果,因為主機名稱不一樣了。我們的採集中主機名稱不能用301重新導向前的URL,要用重新導向之後的URL。

我在以下PHP的例子中介紹下怎麼擷取301定向後真實的URL,目前我知道有兩種方法

1、用get_headers函數;2、用cURL

現介紹利用get_headers() 函數擷取http頭
php 內建的get_headers()取得伺服器響應一個 HTTP 要求所發送的所有標題。 擷取301狀態肯定沒問題。

301定向的例子:
google.com 會301跳轉至 www.google.com
再www.google.com 會302跳轉至 www.google.com.hk

我寫了個php函數 其php函數作用:
輸入 google.com 得到 www.google.com.hk
輸入 www.google.com 得到 www.google.com.hk
輸入 www.google.com.hk 得到 www.google.com.hk

<?php

/*

@param str $url 查詢$return str  定向後的url的真實url

*/
function getrealurl($url){

$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;}

}

$url = ‘http://google.com‘;
$url = getrealurl($url);
echo ‘真實的url為:‘.$url;
//真實的url為:http://www.google.com.hk/

?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.