PHPCMS 雖然搭建 PC 端網站相當方便,但內建的手機站功能較弱,模板控制不靈活。本文記錄如何通過自定義函數判斷移動端訪問,並動態切換模板目錄,實現獨立的手機站體驗。
編輯 phpcms/libs/functions/extention.func.php,加入 check_wap() 函數,根據 HTTP_USER_AGENT 等頭部信息判斷是否為手機瀏覽器:
<?php
// 判斷是否手機訪問
function check_wap() {
if (isset($_SERVER['HTTP_VIA'])) return true;
if (isset($_SERVER['HTTP_X_NOKIA_CONNECTION_MODE'])) return true;
if (isset($_SERVER['HTTP_X_UP_CALLING_LINE_ID'])) return true;
if (strpos(strtoupper($_SERVER['HTTP_ACCEPT']), "VND.WAP.WML") > 0) {
$br = "WML";
} else {
$browser = isset($_SERVER['HTTP_USER_AGENT']) ? trim($_SERVER['HTTP_USER_AGENT']) : '';
if (empty($browser)) return true;
$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','opera mobi','openwave','nexusone','cldc','midp','wap','mobile'
);
if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", $browser) && strpos($browser, 'ipad') === false) {
$br = "WML";
} else {
$br = "HTML";
}
}
return $br == "WML";
}
?>
在 phpcms/templates/default/ 下建立 mobile 資料夾,存放手機版模板文件,檔名需與 PC 端對應模板一致(如 index.html、list.html、show.html)。
編輯 phpcms/templates/modules/content/index.php,在頻道頁、列表頁、內容頁加載模板處加入判斷:
if (check_wap()) {
include template('mobile', $template);
} else {
include template('content', $template);
}
<a href="index.php?m=content&c=index&a=show&catid=25&id={$r['id']}">