如何判断访问者是否正在通过手机访问网站

How to tell if a visitor is accessing a website from a mobile phone?

本文关键字:手机 网站 访问 是否 何判断 判断 访问者      更新时间:2023-09-26

我不确定我是否以正确的方式问。让我解释一下...我注意到Facebook"不是"响应式网页,因为当我在笔记本电脑上更改浏览器的宽度时,facebook.com 在我这样做时不会改变。另一方面,当我使用手机并在浏览器中运行时,facebook.com 已经知道我正在使用移动设备,并且它的大小适合我的设备。

问题:它是如何工作的,是某种技巧来优化我们的网站吗?

我不知道Facebook的确切情况,但是如果没有使用JavaScript或CSS媒体查询进行检测的迹象,那么他们可能正在以老派的方式进行,即使用用户代理字符串。

每当您向网站发出请求时,您的浏览器都会在请求标头中发送一个字符串,在我的例子中是:

User-Agent: Mozilla/5.0 (X11; Linux i686; rv:32.0) Gecko/20100101 Firefox/32.0 Iceweasel/32.0a2

收到请求的服务器可以使用该字符串来了解您正在使用的操作系统和浏览器,您可以看到在我的情况下,操作系统是 Debian,浏览器是 Iceweasel(=firefox),您可以 99% 确定我正在台式计算机上浏览。

我相信用户代理将是你最好的选择。

navigator.userAgent

当我们在桌面上浏览时,服务器检测到我们在桌面上,它只是发送无响应的 FB 的默认(桌面)索引页,但另一方面,如果我们使用其他客户端,例如平板电脑或移动设备,服务器会检测到它.所以它会将 Web 文档重定向到 FB 的其他移动友好页面,或者它会为它更改 CSS,这与桌面 page.it 表示不同该服务器检测我们的设备和浏览器。可用于检测的此类 PHP 检测脚本之一是:

//php  technique
<?php
$agent = $_SERVER['HTTP_USER_AGENT']; // Put browser name into local variable
if (preg_match("/iPhone/", $agent)) { 
header("location: iphone_home.html");
} else if (preg_match("/android/", $agent)) { 
header("location: android_home.html");
}?>
//javascript technique
<script language="javascript" type="text/javascript">
var agent = navigator.userAgent.toLowerCase();
if (agent.indexOf('iphone') != -1) { // iPhone Device
    // If it is an iPhone put specific code to run here for iPhone users
} else if (agent.indexOf('android') != -1) { // Google phones running Android OS
    // If it is a Google phone put specific code to run here for Android users
}
</script>
//php technique to detect OS and browser of user
<?php
$agent = $_SERVER['HTTP_USER_AGENT']; 
$browserArray = array(
    'Windows Mobile' => 'IEMobile',
'Android Mobile' => 'Android',
'iPhone Mobile' => 'iPhone',
'Firefox' => 'Firefox',
    'Google Chrome' => 'Chrome',
    'Internet Explorer' => 'MSIE',
    'Opera' => 'Opera',
    'Safari' => 'Safari'
); 
foreach ($browserArray as $k => $v) {
if (preg_match("/$v/", $agent)) {
     break;
}   else {
 $k = "Browser Unknown";
}
} 
$browser = $k;
$osArray = array(
    'Windows 98' => '(Win98)|(Windows 98)',
    'Windows 2000' => '(Windows 2000)|(Windows NT 5.0)',
'Windows ME' => 'Windows ME',
    'Windows XP' => '(Windows XP)|(Windows NT 5.1)',
    'Windows Vista' => 'Windows NT 6.0',
    'Windows 7' => '(Windows NT 6.1)|(Windows NT 7.0)',
    'Windows NT 4.0' => '(WinNT)|(Windows NT 4.0)|(WinNT4.0)|(Windows NT)',
'Linux' => '(X11)|(Linux)',
'Mac OS' => '(Mac_PowerPC)|(Macintosh)|(Mac OS)'
); 
foreach ($osArray as $k => $v) {
if (preg_match("/$v/", $agent)) {
     break;
}   else {
 $k = "Unknown OS";
}
} 
$os = $k;
echo $agent;
echo "<h2>You are using: <em>$browser - $os</em></h2>";
?>