PHP獲取動態跳轉後的真實連結

dead_lee發表於2021-09-09

網站的跳轉連結經常為本站連結加上一些引數來跳轉,如何使用php獲取跳轉後的連結呢?
php程式碼如下:

    //echo get_redirect_url('');//輸出結果為: 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;

    }}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/4686/viewspace-2809483/,如需轉載,請註明出處,否則將追究法律責任。

相關文章