php如何判斷是手機(jī)還是電腦
有時(shí)我們需要知道用戶(hù)當(dāng)前的設(shè)備,以便進(jìn)行業(yè)務(wù)處理,例如pc就跳轉(zhuǎn)pc站,手機(jī)就跳轉(zhuǎn)手機(jī)站,下面介紹一種判斷的方法。
-
首先php獲取$_SERVER['HTTP_USER_AGENT']的值;
-
然后比對(duì)各個(gè)瀏覽器特定的字符串;
-
最后通過(guò)比對(duì)結(jié)果就能夠判斷是手機(jī)還是電腦了。
代碼如下:
/** * * 根據(jù)php的$_SERVER['HTTP_USER_AGENT'] 中各種瀏覽器訪問(wèn)時(shí)所包含各個(gè)瀏覽器特定的字符串來(lái)判斷是屬于PC還是移動(dòng)端 * @author discuz3x * @lastmodify 2014-04-09 * @return BOOL */ function checkmobile() { global $_G; $mobile = array(); //各個(gè)觸控瀏覽器中$_SERVER['HTTP_USER_AGENT']所包含的字符串?dāng)?shù)組 static $touchbrowser_list =array('iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini', 'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung', 'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser', 'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource', 'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone', 'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop', 'benq', 'haier', '^lct', '320x320', '240x320', '176x220'); //window手機(jī)瀏覽器數(shù)組【猜的】 static $mobilebrowser_list =array('windows phone'); //wap瀏覽器中$_SERVER['HTTP_USER_AGENT']所包含的字符串?dāng)?shù)組 static $wmlbrowser_list = array('cect', 'compal', 'ctl', 'lg', 'nec', 'tcl', 'alcatel', 'ericsson', 'bird', 'daxian', 'dbtel', 'eastcom', 'pantech', 'dopod', 'philips', 'haier', 'konka', 'kejian', 'lenovo', 'benq', 'mot', 'soutec', 'nokia', 'sagem', 'sgh', 'sed', 'capitel', 'panasonic', 'sonyericsson', 'sharp', 'amoi', 'panda', 'zte'); $pad_list = array('pad', 'gt-p1000'); $useragent = strtolower($_SERVER['HTTP_USER_AGENT']); if(dstrpos($useragent, $pad_list)) { return false; } if(($v = dstrpos($useragent, $mobilebrowser_list, true))){ $_G['mobile'] = $v; return '1'; } if(($v = dstrpos($useragent, $touchbrowser_list, true))){ $_G['mobile'] = $v; return '2'; } if(($v = dstrpos($useragent, $wmlbrowser_list))) { $_G['mobile'] = $v; return '3'; //wml版 } $brower = array('mozilla', 'chrome', 'safari', 'opera', 'm3gate', 'winwap', 'openwave', 'myop'); if(dstrpos($useragent, $brower)) return false; $_G['mobile'] = 'unknown'; //對(duì)于未知類(lèi)型的瀏覽器,通過(guò)$_GET['mobile']參數(shù)來(lái)決定是否是手機(jī)瀏覽器 if(isset($_G['mobiletpl'][$_GET['mobile']])) { return true; } else { return false; } } /** * 判斷$arr中元素字符串是否有出現(xiàn)在$string中 * @param $string $_SERVER['HTTP_USER_AGENT'] * @param $arr 各中瀏覽器$_SERVER['HTTP_USER_AGENT']中必定會(huì)包含的字符串 * @param $returnvalue 返回瀏覽器名稱(chēng)還是返回布爾值,true為返回瀏覽器名稱(chēng),false為返回布爾值【默認(rèn)】 * @author discuz3x * @lastmodify 2014-04-09 */ function dstrpos($string, $arr, $returnvalue = false) { if(empty($string)) return false; foreach((array)$arr as $v) { if(strpos($string, $v) !== false) { $return = $returnvalue ? $v : true; return $return; } } return false; }