Question

I'm pretty new to PHP so please bear with me.

I'm trying to log the User Agents for mobile phones accessing my site. I'm doing this by checking the $_SERVER['HTTP_USER_AGENT'] value.

Ran into a small issue where I noticed if the person was accessing my site via opera mini then opera mini moves the actual user agent into a header value identified as X-OperaMini-Phone-UA:

So I'm looking for the PHP code which will extract this from the header (if present) and if not, identify it as NA for database logging purposes.

This is the code I'm currently using for logging which was written by someone else

<?php
mysql_connect('server.com', 'dbuser', 'dbpass');
$url = mysql_real_escape_string("http://$_SERVER[SERVER_NAME]$_SERVER[REQUEST_URI]");
$fn = mysql_real_escape_string($_SERVER['SCRIPT_NAME']);
$ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$ref = mysql_real_escape_string($_SERVER['HTTP_REFERER']);
$ua = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);
mysql_select_db('db');
mysql_query("INSERT INTO `record` VALUES ('$url', '$fn', NOW(),'$ip', '$ref','$ua')");
?>

So, now I'm adding a few field named opera_user_agent and I want to log the Opera user agent if there is one and use 'NA' if there isn't.

Was it helpful?

Solution

You can fetch the value with getallheaders:

$headers = getallheaders();

if (array_key_exists("X-OperaMini-Phone-UA", $headers))
{
    $ua = mysql_real_escape_string($headers["X-OperaMini-Phone-UA"]);
}
else 
{
    $ua = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);
}

Another approach is to add the header to an environment variable with a rewriterule in .htaccess, and then pick it up via $_SERVER as usual:

RewriteRule .* - [E=X-OPERAMINI-PHONE-UA:%{HTTP:X-OperaMini-Phone-UA}]

OTHER TIPS

You can use $_SERVER['HTTP_X_OPERAMINI_PHONE_UA'] as well:

if(!empty($_SERVER['HTTP_X_OPERAMINI_PHONE_UA'])){
    // use $_SERVER['HTTP_X_OPERAMINI_PHONE_UA']
}else{
    // use default $_SERVER['HTTP_USER_AGENT']
}

On October 2012 Opera suggested new header called Device-Stock-UA. After that time new Opera Mini/Mobile browsers will use new Device-Stock-UA and old X-OperaMini-Phone-UA headers. https://dev.opera.com/blog/introducing-device-stock-ua/

This parameter is defined like this:

The value of this header matches that of the stock user agent bundled with the operating system on which Opera Mobile or Mini is running.

Regarding to that update I created this function:

public static function getUserAgentDevice() {
    if (isset($_SERVER['HTTP_X_OPERAMINI_PHONE_UA'])) {
        return $_SERVER['HTTP_X_OPERAMINI_PHONE_UA'];
    }
    if (isset($_SERVER['HTTP_DEVICE_STOCK_UA'])) {
        return $_SERVER['HTTP_DEVICE_STOCK_UA'];
    }
    return $_SERVER['HTTP_USER_AGENT'];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top