現在移動互聯網越來越發達,很多的網站都普及了手機端浏覽,為了更好的讓網頁在手機端顯示,我們都選擇了使用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函數庫中調用:
<?php function 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; ?>
以上所述就是本文的全部內容,希望大家喜歡。