PHP和JS判斷手機還是電腦訪問

來源:互聯網
上載者:User

標籤:

當使用者使用手機等移動終端訪問網站時,我們可以通過程式檢測使用者終端類型,如果是手機使用者,則引導使用者訪問適配手機螢幕的移動網站。本文將介紹分別使用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; } 
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.helloweba.com") }else{     document.write("請使用手機訪問."); } 

 

PHP和JS判斷手機還是電腦訪問

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.