現(xiàn)在有很多的短網(wǎng)址應(yīng)用,點(diǎn)擊就跳轉(zhuǎn)到縮短之前的網(wǎng)址了,那今天我們就來看一下,PHP如何獲取短網(wǎng)址跳轉(zhuǎn)之前的網(wǎng)址,其實(shí)也很簡單,就是用php的get_headers 函數(shù),取得Response Headers,之后慢慢分析就行了。
給出具體實(shí)現(xiàn)方法,代碼如下:
- $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;
- }
實(shí)例二,代碼如下:
- //
- echo get_redirect_url('http://m.survivalescaperooms.com');
- //輸出結(jié)果為: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;
- }
- }
新聞熱點(diǎn)
疑難解答