當用戶使用手機等移動終端訪問網站時,我們可以通過程序檢測用戶終端類型,如果是手機用戶,則引導用戶訪問適配手機屏幕的移動站點。本文將介紹分別使用PHP和JAVASCRIPT代碼判斷用戶終端類型。
PHP版
我們使用PHP的$_SERVER['HTTP_USER_AGENT']來獲取手機用戶浏覽器的用戶代理,然後匹配已有的各種手機浏覽器代理庫,如果含有匹配的關鍵字,則判斷為手機(移動終端)用戶。
function is_mobile() { $user_agent = $_SERVER['HTTP_USER_AGENT']; $mobile_agents = array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi", "android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio", "au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu", "cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ", "fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi", "htc","huawei","hutchison","inno","ipad","ipaq","iphone","ipod","jbrowser","kddi", "kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo", "mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-", "moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia", "nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-", "playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo", "samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank", "sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit", "tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin", "vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce", "wireless","xda","xde","zte"); $is_mobile = false; foreach ($mobile_agents as $device) { if (stristr($user_agent, $device)) { $is_mobile = true; break; } } return $is_mobile; }
上述代碼中函數is_mobile()來判斷用戶終端類型,將收集到的當今各種手機的HTTP_USER_AGENT歸結到數組$mobile_agents中,並進行匹配。使用時只需調用函數is_mobile()。如以下代碼表示,當匹配用戶為手機訪問時,頁面跳轉到網站手機版m.jb51.net。
if (is_mobile()) { header('Location:http://m.jb51.net'); } else { echo '請使用手機訪問.'; }
Javascript版
您也可以直接在前端頁面上加入一段Javascript腳本來判斷用戶的終端類型。Javascript也是通過獲取浏覽器的user-agent信息,然後匹配已有的user-agent信息庫。
if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry| WebOS|Symbian|Windows Phone|Phone)/i))) { location.replace("http://m.jb51.net") }else{ document.write("請使用手機訪問."); }
以上代碼還不是很完善,有興趣的朋友歡迎補充。
當然,我們也可以通過響應式布局來匹配各種不同屏幕,這樣可以節約開發成本,但是當客戶對移動網站的功能需求,對於獨立的移動站點最好是采用在網站入口處判斷用戶訪問終端類型,一般是我們在主站首頁就做判斷,如果是手機訪客則跳轉到手機版頁面,否則按正常PC方式訪問頁面。