【问题标题】:Detect Mobile or Windows PHP [duplicate]检测移动或 Windows PHP [重复]
【发布时间】:2016-01-13 17:06:17
【问题描述】:

我想建立一个网站,但我搞砸了。我想制作两个版本,一个用于台式机,一个用于移动设备,但不知道如何重定向人们.. 我想要两个文件夹,移动设备和网络以及文件 index.php。如果他们使用手机,如果他们使用 PC 重定向到 Web 文件夹,我想在移动文件夹中重定向。

我怎么能这样做?谢谢

对不起英文

【问题讨论】:

  • 为什么不直接使用媒体查询呢?尤其是在这个时代。相信我,你会努力工作的。
  • detectmobilebrowsers.com 提供了额外的方法。

标签: php redirect mobile web


【解决方案1】:

案例 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>

【讨论】:

    猜你喜欢
    • 2013-03-14
    • 2020-10-17
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 2010-11-20
    • 2012-01-29
    相关资源
    最近更新 更多