判断目前浏览网站的用户使用的浏览器版本有多种算法。其中最有用的也是最容易实现的一种方法是使用$_SERVER['HTTP_USER_AGENT']的内容,返回的字符串表示可以全面的描述目前访问网站的系统。一旦有了这个字符串我们可以使用正则表达式将不同部分分解到相应的变量中,然后使用。
第二种方法时使用get_browser()函数,遗憾的是这种方法并不可靠,需要进行额外的服务器配置,需要一个最新的browscap.ini文件(此文件可以去网上下载),然后对php.ini文件进行配置
;browsecap =
改为
browscap = my/path/browscap.ini
这次我们主要介绍第一种方法,他几乎可以在所有的php5平台上工作
代码:
//filename.php
//这里定义一个类brower来判断浏览器种类和操作系统平台
class browser {
//Our private variables.
private $browseragent;
private $browserversion;
private $browserplatform;
//函数来更改相应的变量,平台,浏览器,版本
//A function to set the browser agent.
private function setagent($newagent) {
$this->browseragent = $newagent;
}
//A function to set the browser version.
private function setversion($newversion) {
$this->browserversion = $newversion;
}
//A function to set the browser platform.
private function setplatform($newplatform) {
$this->browserplatform = $newplatform;
}
//判断返回的字符串提取对应的字符做出判断
//A function to determine what browser and version we are using.
private function determinebrowser () {
//正则表达判断IE以及版本
if (ereg('MSIE ([0-9].[0-9]{1,2})',$_SERVER['HTTP_USER_AGENT'],$version)) {
$this->setversion($version[1]);
$this->setagent("IE");
//判断opera以及版本
} else if (ereg( 'Opera ([0-9].[0-9]{1,2})',$_SERVER['HTTP_USER_AGENT'],$version)) {
$this->setversion($version[1]);
$this->setagent("OPERA");
} else if (ereg( 'Mozilla/([0-9].[0-9]{1,2})',$_SERVER['HTTP_USER_AGENT'],$version)) {
$this->setversion($version[1]);
$this->setagent("MOZILLA");
} else {
$this->setversion("0");
$this->setagent("OTHER");
}
}
//A function to determine the platform we are on.
//判断平台的种类
private function determineplatform () {
if (strstr ($_SERVER['HTTP_USER_AGENT'],"Win")) {
$this->setplatform("Win");
} else if (strstr ($_SERVER['HTTP_USER_AGENT'],"Mac")) {
$this->setplatform("Mac");
} else if (strstr ($_SERVER['HTTP_USER_AGENT'],"Linux")) {
$this->setplatform("Linux");
} else if (strstr ($_SERVER['HTTP_USER_AGENT'],"Unix")) {
$this->setplatform("Unix");
} else {
$this->setplatform("Other");
}
}
//A function to return our current browser.
//返回我们想要的信息,浏览器版本以及操作平台
public function getbrowser (){
$this->determinebrowser ();
return $this->browseragent . " " . $this->browserversion;
}
//A function to return our current platform.
public function getplatform (){
$this->determineplatform ();
return $this->browserplatform;
}
}
//Now, we simply create a new instance of our browser class.
$mybrowser = new browser ();
//显示浏览器的版本和操作平台
echo "Browser: " . $mybrowser->getbrowser() . "
";
echo "Platform: " . $mybrowser->getplatform() . "
";
//打印整个字符串,我们可以用这个参考学习
echo $_SERVER['HTTP_USER_AGENT'];
?>
运行结果(本人系统xp&firefox)
Browser: MOZILLA 5.0
Platform: Win
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7
阅读(3101) | 评论(1) | 转发(0) |