案例 1:将网站重定向到移动版本
假设我们有一个普通网站,如果从移动设备查看,我们需要将其重定向到移动版本。移动检测所需的所有代码都在单个文件“Mobile_Detect.php”中,我们可以将其包含在我们的网页或主索引文件中。为了简化讨论,我们假设您有一个带有单个索引文件的网站“example1.com”,如果检测到移动设备,则需要重定向到“mobile.example1.com”。我们需要将以下内容放在‘example1.com’的索引文件的头文件中。
/* Change path info depending on your file locations */
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
if($detect->isMobile()) {
header('Location: http://mobile.example1.com/');
exit;
}
案例2:根据设备加载不同的资源
我们可以根据用户设备配置文件加载或修改现有内容。例如,我们可以为手机或平板电脑加载不同的 CSS。
$detect = new Mobile_Detect;
if($detect->isMobile() || $detect->isTablet()) {
echo "<link rel='stylesheet' href='mobile.css type='text/css' />";
} else {
echo "<link rel='stylesheet' href='style.css type='text/css' />";
}
您也可以使用 Javascript:
<script type="text/javascript">
<!--
if (screen.width <= 800) {
window.location = "http://m.domain.com";
}
//-->
</script>
或
您可以使用 .htaccess 重定向来根据浏览器支持的 MIME 类型转移访问者。例如,如果用户的浏览器接受包含 WML(无线标记语言)的 mime 类型,那么它很可能是移动设备。
下面的代码应该放在你的 .htaccess 文件中:
RewriteEngine On
# Check for mime types commonly accepted by mobile devices
RewriteCond %{HTTP_ACCEPT} "text\/vnd\.wap\.wml|application\/vnd\.wap\.xhtml\+xml" [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^ http://m.domain.com%{REQUEST_URI} [R,L]
如果您有 2 个站点,每个设备都有一个(这里不是最好的做法),您可以在根目录下拥有一个 index.php 文件:
<script type="text/javascript">
<!--
if (screen.width <= 800) {
window.location = "http://your.domain.com/mobile";
} else { window.location = "http://your.domain.com/desktop"; }
//-->
</script>