PHP 判斷進入移動端
阿新 • • 發佈:2019-01-05
判斷是否為手機引入不同模板
function isMobile() {
// 如果有HTTP_X_WAP_PROFILE則一定是移動裝置
if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
return true;
}
// 如果via資訊含有wap則一定是移動裝置,部分服務商會遮蔽該資訊
if (isset($_SERVER['HTTP_VIA'])) {
// 找不到為flase,否則為true
return stristr($_SERVER['HTTP_VIA'], "wap" ) ? true : false;
}
// 腦殘法,判斷手機發送的客戶端標誌,相容性有待提高。其中'MicroMessenger'是電腦微信
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$clientkeywords = array('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu' ,'android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile','MicroMessenger');
// 從HTTP_USER_AGENT中查詢手機瀏覽器的關鍵字
if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
return true;
}
}
// 協議法,因為有可能不準確,放到最後判斷
if (isset ($_SERVER['HTTP_ACCEPT'])) {
// 如果只支援wml並且不支援html那一定是移動裝置
// 如果支援wml和html但是wml在html之前則是移動裝置
if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
return true;
}
}
return false;
}
根據判斷跳轉到手機網站
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
$uachar = "/(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)/i";
if(($ua == '' || preg_match($uachar, $ua))&& !strpos(strtolower($_SERVER['REQUEST_URI']),'wap'))
{
$Loaction = 'http://m.domain.com'; //填寫需要跳轉的地址
if (!empty($Loaction))
{
header("Location: $Loaction\n");
exit;
}
}