標籤:
如何用php判斷一個用戶端是手機還是電腦?其實很簡單,開發人員都知道,通過瀏覽器訪問網站時,瀏覽器都會向伺服器發送UA,即User Agent(使用者代理)。不同瀏覽器、同一瀏覽器的不同版本、手機瀏覽器、電腦端的瀏覽器的UA都是不一樣的。我們只要寫代程式擷取這段UA,然後判斷UA是什麼,然後就可以區分出是手機還是電腦了。
下面,通過PHP代碼來判斷訪客的瀏覽器UA是否為手機瀏覽器,然後自動跳轉到相應的頁面:
<?phpfunction is_mobile(){ //Regex,批配不同手機瀏覽器UA關鍵詞。 $regex_match="/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|"; $regex_match.="htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|"; $regex_match.="blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|"; $regex_match.="symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|"; $regex_match.="jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220"; $regex_match.=")/i"; return isset($_SERVER[‘HTTP_X_WAP_PROFILE‘]) or isset($_SERVER[‘HTTP_PROFILE‘]) or preg_match($regex_match, strtolower($_SERVER[‘HTTP_USER_AGENT‘])); //如果UA中存在上面的關鍵詞則返回真。} if(is_mobile()) { //如果為真,則進行WAP頁面。 header( "HTTP/1.1 301 Moved Permanently"); header("Location: http://www.966266.com/wap.php"); }else { //如果為假,則進行WEB頁面。 header( "HTTP/1.1 301 Moved Permanently"); header("Location: http://www.966266.com/"); }?>
根據瀏覽器UA資訊進行跳轉(移動和pc)