Wednesday, April 1, 2009

Finding the User Agent

In the previous post we have seen what is User agent, what does UA does and where it is used.
In this post we will find out how can we optain the UA name.
If we are talking about a web browsers client the info about UA can be optained from http headers in many server environments. Below we will quote examples for the major scripting languages:

1. PHP
In PHP, the value of HTTP headers are stored in the $_SERVER array. Here is the code for retrieving HTTP headers:
$user_agent = $_SERVER["HTTP_USER_AGENT"];
$user_agent contains the UA name and version.

2. Perl
In Perl, the values of HTTP headers are stored in the %ENV hash. Here is the code for retrieving HTTP headers:
$user_agent = $ENV{"HTTP_USER_AGENT"};
Again $user_agent contains the UA name and version.

3. Javascript
In JScript, the code for reading HTTP headers should look like this:
var user_agent = Request.ServerVariables("HTTP_USER_AGENT");
user_agent contains the UA name and other info.

4. In Java Servlet or JSP, you can use the getHeader() method of the javax.servlet.http.HttpServletRequest object to retrieve the value of HTTP headers. Here is the code for reading HTTP headers:
String user_agent = request.getHeader("user-agent");
user_agent contains the UA name and other info.

5. In ASP, you can use the ServerVariables collection of the Request object to retrieve the value of HTTP headers.
user_agent = Request.ServerVariables("HTTP_USER_AGENT")

In the next post we will find out how to detect the Client Device Capabilities.

No comments: