---
title: "对User Agent的检测与模拟"
author: "xwv"
date: "2013-11-15T18:08:05Z"
tags: []
categories: ["互联网"]
slug: "user-agent"
draft: false
lastmod: "2013-11-15T18:10:38Z"
id: 1975730
url: "https://xwv.iteye.com/blog/1975730"
---

在PHP项目中,需要对送至服务器端的Http请求,检测其User Agent,如何做?

      在Http请求消息头中,包含一个field: User-Agent,表明了发送请求的Consumer.在服务器端程序中,

则通过此信息来检测.

      可以自己编写代码,或者利用第三方提供的函数/类库,来帮助进行.

      在PHP中,可以通过变量$\_SERVER\['HTTP\_USER\_AGENT'] ,函数get\_browser(),来完成.下面这个

blog有较多描述:

      [php判断客户端浏览器的类型](http://luochangzhi.iteye.com/blog/1887263)

      如果是采用第三方提供的库,则能更快速地达到目的.下面的这个git库,就提供了一个可用的类:

      https://github.com/mavrick/Browser.php

 

      在实践过程中,上述的类中没有提供对Baiduspider的检测,就需要自己进行定制了.定制过程中

最主要的关注信息,是各个User Agent的具体字符串内容.有很多站点提供此类信息,比如:

      1. http://www.httpuseragent.org/

      2. http://www.useragentstring.com/

      当然,去官网能找到最新的信息.比如想了解Google的网页搜索robot使用的User Agent,可以看看这里:

      https://support.google.com/webmasters/answer/1061943

 

      接下来,需要使用某种方式来模拟某个特定User Agent的Http请求,以便测试.有什么工具?

      能够达到模拟测试的工具较多.有专门完成此任务浏览器端扩展.在下面的web中:

      [How to Switch Your User-Agent to Googlebot](http://www.searchenginejournal.com/how-to-switch-your-user-agent-to-googlebot/7249/)

      就提到了User-agent switcher,这是一个可用于Firefox的扩展,其User Agent 列表可自定义;作者提供的

最新的列表文件,可以[在此找到](http://forums.chrispederick.com/discussion/7/a-large-regularly-updated-import-list-of-user-agents).附件中是当前的最新数据.

      上面的web中还提到另一个工具Header detector,没有实际使用过.

      同样,有些工具会附带简单的User Agent模拟功能,比如Firefox上的扩展MozBar,它是一个SEO工具栏,

附带了简单的User Agent模拟.

      而搜索引擎自身也可能会提供一些方法.比如Google在Webmaster tools里发布的新工具: Fetch as Googlebot,可以模拟Googlebog抓取网页.