2012-12-25 72 views
2

找我試圖得到什麼頁面訪問者訪問什麼網頁訪客的訪問,PHP

這裏是我的代碼:

$url = $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; 
$urlcomplete = $url; 
$url = explode(".com/",$url); 
$urlcount = count($url); 
$newurl = ''; 
for ($start = 1; $start < $urlcount; $start++) { 
    if ($newurl != '') { 
     $newurl .= '.com/'; 
    } 
    $newurl .= $url[$start];  
} 
$url = explode('/',$newurl); 
$urlcount = explode('?',end($url)); 
$url[count($url) - 1] = $urlcount[0]; 
$urlcount = count($url); 

通過使用上面的代碼,所有的子頁面會店在$ url中。

https://stackoverflow.com/questions/ask

$url[0] = 'questions' 
$url[1] = 'ask' 

只想問一句,這是很好的方式,或者還有其他更好的辦法?

+0

你需要一個正則表達式。當你有一個非'.com'域時會發生什麼? – Kermit

+2

你試圖在人力方面完成什麼? –

+0

從http://stackoverflow.com/questions/ask獲得什麼url的部分是你想要獲得的。 –

回答

2

首先預先SERVER_NAMEREQUEST_URI,然後試圖分裂它,是毫無意義的。這應該是一個簡單的解決方案:

# first, split off the query string, if any: 
list($path) = explode('?', $_SERVER['REQUEST_URI'], 2); 

# then just split the URL path into its components: 
$url = explode('/', ltrim($path, '/')); 

ltrim將刪除路徑中的任何斜線開頭,讓$url[0]不會是空的。

請注意,如果路徑以斜槓結尾,則$url數組末尾可能仍有空元素。你可能擺脫它通過使用trim而不是ltrim,但你可能不希望,因爲尾部的斜槓是像解析相對URL的東西很重要。

+0

謝謝。這比我的代碼好多了。 –