Decode a user agent

Is there an easy way/built in function to decode a PHP user agent? If not, how would I do this?

The user agent is stored in $_SERVER['HTTP_USER_AGENT']. You would have to give more specifics about 'decode’ing a user agent.

1 Like

I had a go at doing that a little while ago. It’s very messy and I came to the conclusion it wasn’t worth it.

My code FWIW is below, but it misses a lot of browsers…

<?php
$uAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';

$trans = array(
  'OPR'      => 'Opera',
  'UBrowser' => 'UC Browser',
  'YaBrowser'=> 'Yandex',
  'Edg'      => 'Edge',
  'MSIE'     => 'Internet Explorer',
  // yes, I know Trident isn't IE but it's the string that identifies IE11
  'Trident'  => 'Internet Explorer 11.0'
);

// The order is important!
$browsers = [
  'PaleMoon',
  'Firefox',
  'OPR',
  'Edge',
  'Edg',
  'UBrowser',
  'YaBrowser',
  'Chrome',
  'Safari',
  'MSIE',
  'Trident',
  'Unknown'
];

foreach ($browsers as $browser) {
  if (false !== $pos = strpos($uAgent, $browser))
    break;
}

$sub1 = substr($uAgent, $pos);   // from browser name to end
$sub2 = explode(' ', $sub1);     // just browser name and version
$sub3 = explode('/', $sub2[0]);  // split browser name and version
$sub4 = explode('.', $sub3[1]);  // get sub, sub sub versions etc

echo '<p>User agent: ', $uAgent, '</p>', "\n";
$browserName = $browser;
if (isset($trans[$browser]))
  $browserName = $trans[$browser];
echo '<p>Your browser is ', $browserName;
if ($browser !== 'Unknown' && $browser !== 'Trident')
  echo ' ', $sub4[0], '.', $sub4[1], '</p>';
1 Like

There is also this User Agent parser on packagist: https://packagist.org/packages/ua-parser/uap-php

Can be installed using composer https://getcomposer.org/

1 Like

Thanks for all the replies! I think I’ll check out this package, it looks quite promising.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.