PHP教程:php獲取多次跳轉後真實的url地址

<?php
/*
    獲取多次跳轉後真實的url
    @param str $url 查詢
    $return str  定向後的url的真實url
 */
function getrealurl($url){
    $header = @get_headers($url,1);  //默認第二個參數0,可選1,返回關聯數組
    if(!$header){
        exit('無法打開此網站'.$url);
    }
    //var_dump($header);
    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 = 'https://git.io/JtLZy';
$url = getrealurl($url);
echo '真實的url爲:'.$url;
<?php
/*
    獲取多次跳轉後真實的url
    @param str $url 查詢
    $return str  定向後的url的真實url
 */
function getrealurl($url){
    $header = @get_headers($url,1);  //默認第二個參數0,可選1,返回關聯數組
    if(!$header){
        exit('無法打開此網站'.$url);
    }
    //var_dump($header);
    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 = 'https://git.io/JtLZy';
$url = getrealurl($url);
echo '真實的url爲:'.$url;

通過PHP的get_headers()函數來獲取跳轉後的網址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章