phpmobileopera-mini

Using PHP to log value in header conditionally


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.


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}]