User Agent Parsing with PHP, JavaScript, or Python

By  on  

Saying the phrase "user agent" or "user agent string" is tantamount to saying a swear word. Developers used to use the user agent to detect if a browser had a given feature, instead of, you know, checking to see if the feature actually existed via object or property detection. Those days are behind us though, but one of the web's dirty secrets is that the user agent still has many uses. One frequent use, for example, is detecting which mobile theme to offer up; this detection can be done on both the client and server sides. I recently found Tobie Langel's ua-parser, a great repo which provides simple UA parsing in JavaScript, PHP, and Python.

Sample User Agent

'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3'

JavaScript Usage

var uaParser = require('ua-parser'),
	uaParser.parse(navigator.userAgent);

console.log(ua.tostring());  // -> "Safari 5.0.1"

console.log(ua.toVersionString());  // -> "5.0.1"

console.log(ua.family);  // -> "Safari"

console.log(ua.major); // -> 5

console.log(ua.minor);  // -> 0

console.log(ua.patch);  // -> 1

PHP Usage

// Require the library
require("UAParser.php");

// Parse the UA
$result = UA::parse();

// Get loads of information! :)
print $result->full;  // -> Chrome 16.0.912/Mac OS X 10.6.8

print $result->browserFull;  // -> "Chrome 16.0.912"

print $result->browser;  // -> "Chrome"

print $result->version;  // -> "16.0.912"

print $result->major;  // -> 16 (minor, build, & revision also available)

print $result->osFull;  // -> "Mac OS X 10.6.8"

print $result->os;  // -> "Mac OS X"

print $result->osVersion;  // -> "10.6.8"

print $result->osMajor;  // -> 10 (osMinor, osBuild, & osRevision also available)

Python Usage

# Import the lib
from ua_parser import user_agent_parser

# Parse the user agent
user_agent_parser.Parse(request.META.get('HTTP_USER_AGENT'))

print result_dict['user_agent']
# {'major': '5', 'minor': '1', 'family': 'Mobile Safari', 'patch': None}

print result_dict['os']
# {'major': '5', 'patch_minor': None, 'minor': '1', 'family': 'iOS', 'patch': None}

print result_dict['device']
# {'is_spider': False, 'is_mobile': True, 'family': 'iPhone'}

The code samples above are all easily recognizable by those who can use them; using user agent information is simple, and the API is as well. Well done to Tobie for this nice library.

Recent Features

  • By
    9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

  • By
    How to Create a RetroPie on Raspberry Pi – Graphical Guide

    Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices.  While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...

Incredible Demos

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

  • By
    Chris Coyier’s Favorite CodePen Demos IV

    Did you know you can triple-heart things on CodePen? We’ve had that little not-so-hidden feature forever. You can click that little heart button on any Pen (or Project, Collection, or Post) on CodePen to show the creator a little love, but you can click it again...

Discussion

  1. Very helpful! Thanks a lot

  2. this is awesomely handy, thank you!

  3. bn

    JS code sample:
    I had to add the ua variable.

    ua = uaParser.parse(navigator.userAgent);

  4. Thanks alot! :)
    Searched quite a while for such a nice parser

  5. rob

    looking in the php directory at github: https://github.com/tobie/ua-parser/tree/master/php I don’t see a file called “UAParser.php”. I did find a file called uaparser.php in the php/bin directory (https://github.com/tobie/ua-parser/blob/master/php/bin/uaparser.php) which I have tried to run from command line and am running into a missing required file called “vendor/autoload.php”. Where is this autoload.php file? Are there dependencies that I am missing?

  6. Munaza

    Hi,

    I was looking in php directory. I did find a file called uaparser.php in the php/bin directory (https://github.com/tobie/ua-parser/blob/master/php/bin/uaparser.php) which I have tried to run from command line and am running into a missing required file called “vendor/autoload.php”. Where is this autoload.php file? Are there dependencies that I am missing?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!