PHP代碼判斷裝置是手機還是平板電腦(兩種方法),php平板電腦
現在移動互連網越來越發達,很多的網站都普及了手機端瀏覽,為了更好的讓網頁在手機端顯示,我們都選擇了使用CSS媒體查詢製作響應式模版,但這也有弊端,例如某些網站的結構是CMS類型的,太多的內容要顯示,而使用CSS媒體查詢設計響應式,只會隱藏但還是載入了,為了讓手機端更快速的顯示出內容,我們可以使用這個PHP判斷手機裝置代碼,使用這個代碼可以很方便的顯示或不顯示自訂的內容。
在做WEB開發的時候經常會需要用到對行動裝置的頁面匹配,當然可以直接把網站做成響應式的,但如果不想這麼做的話,可以使用PHP對裝置類型進行判斷, 然後顯示相應的介面和內容。今天分享一種使用 PHP 判斷裝置是否是手機/平板的方法,方法來源於WordPress(wp-includes/vars.php:125),適用於大部分類型的手機/平板判 斷:
方法一:
/** * Test if the current browser runs on a mobile device (smart phone, tablet, etc.) * * @staticvar bool $is_mobile * * @return bool */function wp_is_mobile() { static $is_mobile = null; if ( isset( $is_mobile ) ) { return $is_mobile; } if ( empty($_SERVER['HTTP_USER_AGENT']) ) { $is_mobile = false; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.) || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false ) { $is_mobile = true; } else { $is_mobile = false; } return $is_mobile;}
代碼二:
這是PHP判斷手機裝置函數代碼,複製到PHP函數庫中調用:
<?phpfunction is_mobile() {$user_agent = $_SERVER['HTTP_USER_AGENT'];$mobile_browser = Array("mqqbrowser", //手機QQ瀏覽器"opera mobi", //手機opera"juc","iuc",//uc瀏覽器"fennec","ios","applewebKit/420","applewebkit/525","applewebkit/532","ipad","iphone","ipaq","ipod","iemobile", "windows ce",//windows phone"240×320","480×640","acer","android","anywhereyougo.com","asus","audio","blackberry","blazer","coolpad" ,"dopod", "etouch", "hitachi","htc","huawei", "jbrowser", "lenovo","lg","lg-","lge-","lge", "mobi","moto","nokia","phone","samsung","sony","symbian","tablet","tianyu","wap","xda","xde","zte");$is_mobile = false;foreach ($mobile_browser as $device) {if (stristr($user_agent, $device)) {$is_mobile = true;break;}}return $is_mobile;}?>
這是調用代碼,可以加上if判斷:
<?php if(is_mobile()):?>
設定手機端的內容
<?php endif; ?>
以上所述就是本文的全部內容,希望大家喜歡。
http://www.bkjia.com/PHPjc/1062503.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1062503.htmlTechArticlePHP代碼判斷裝置是手機還是平板電腦(兩種方法),php平板電腦 現在移動互連網越來越發達,很多的網站都普及了手機端瀏覽,為了更好的讓...