I originally asked the question because I want to be able to record the browsers and operations systems people use to access my site. Yes, the user agent string can't be trusted, and yes, you shouldn't use browser detection to determine what code to run in JS, but, I'd like to have as accurate as possible statistics.
I did the following.
I'm using a combination of JavaScript and PHP to record the stats. JavaScript to determine what browser and OS (as this is probably the most accurate), and PHP to record it:
The JavaScript comes from Quirksmode, the PHP is rather self evident. I use the MooTools JS framework.
Add the following to the BrowserDetect script:
window.addEvent('domready', function() {
if (BrowserDetect) {
var q_data = 'ajax=true&browser=' + BrowserDetect.browser + '&version=' + BrowserDetect.version + '&os=' + BrowserDetect.OS;
var query = 'record_browser.php'
var req = new Request.JSON({url: query, onComplete: setSelectWithJSON, data: q_data}).post();
}
});
This determines the browser, browser version and OS of the user's browser, and sends it to the record_browser.php
script. The record_browser.php
script just add's the information, along with the PHP session_id
and the current user_id
, if present.
MySQL Table:
CREATE TABLE `browser_detects` (
`id` int(11) NOT NULL auto_increment,
`session` varchar(255) NOT NULL default '',
`user_id` int(11) NOT NULL default '0',
`browser` varchar(255) NOT NULL default '',
`version` varchar(255) NOT NULL default '',
`os` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`),
UNIQUE KEY `sessionUnique` (`session`)
)
PHP Code:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$session = session_id();
$user_id = isset($user_id) ? $user_id ? 0;
$browser = isset($_POST['browser']) ? $_POST['browser'] ? '';
$version = isset($_POST['version']) ? $_POST['version'] ? '';
$os = isset($_POST['os']) ? $_POST['os'] ? '';
$q = $conn->prepare('INSERT INTO browser_detects (`session`, `user`, `browser`, `version`, `os`) VALUES (:session :user, :browser, :version, :os)');
$q->execute(array(
':session' => $session,
':user' => $user_id,
':browser' => $browser,
':version' => $version,
':os' => $os
));
}