首頁  >  文章  >  後端開發  >  php怎麼取得跳轉後的url?

php怎麼取得跳轉後的url?

青灯夜游
青灯夜游原創
2020-11-06 11:56:563253瀏覽

php取得跳轉url的方法:1、使用get_headers函數取得跳轉後的url,該函數可以取得伺服器回應一個HTTP請求所傳送的所有標頭;2、使用fsockopen()函數; 3.使用使用cURL函數。

php怎麼取得跳轉後的url?

推薦:《PHP影片教學

有時候我們會在開發中,常常會遇到有URL 301或302重定向的情況,這時候我們可能需要取得重定向之後的url,下面我們介紹幾個取得重定向url的方法:

1、用get_headers函數

php自帶的get_headers函數可以取得伺服器回應一個HTTP請求所傳送的所有標頭,我們可以嘗試用該函數實作。

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

2、使用fsockopen()內建函數

function get_redirect_url($url){
   $redirect_url = false;
   $url_parts = @parse_url($url);
   if (!$url_parts) return false;
   if (!isset($url_parts['host'])) return false;
   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.1\r\n”;
   $request .= ‘Host: ‘ . $url_parts['host'] . “\r\n”;
   $request .= “Connection: Close\r\n\r\n”;
   fwrite($sock, $request);
   $response = ”;
   while(!feof($sock)) $response .= fread($sock, 8192);
   fclose($sock);
  if (preg_match(‘/^Location: (.+?)$/m’, $response, $matches)){
     return trim($matches[1]);
   } else {
    return false;
  }
}

3、使用cURL函數

function get_redirect_url($url, $referer=”, $timeout = 10) {
   $redirect_url = false;
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_HEADER, TRUE);
   curl_setopt($ch, CURLOPT_NOBODY, TRUE);//不返回请求体内容
   curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);//允许请求的链接跳转
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
   curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
   curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      ‘Accept: */*’,
      ‘User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)’,
      ‘Connection: Keep-Alive’));
   if ($referer) {
     curl_setopt($ch, CURLOPT_REFERER, $referer);//设置referer
   }
   $content = curl_exec($ch);
   if(!curl_errno($ch)) {
     $redirect_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);//获取最终请求的url地址
   }
   return $redirect_url;
}

哪個方法的效果更高一些,可以自行測試一下。

更多程式相關知識,請造訪:程式設計入門! !

以上是php怎麼取得跳轉後的url?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn