How to extract User-Agent in PHP

Updated: January 12, 2024 By: Guest Contributor Post a comment

Overview

In web development, determining the type of device or browser a user is using can be quite critical for various features such as analytics, compatibility adjustments, or simply custom tailored experiences. A common way to achieve this is by extracting the User-Agent string from the HTTP request headers. In PHP, this task is a straightforward process, thanks to its global arrays and predefined functions. This tutorial will guide you through the steps needed to extract and parse the User-Agent string in PHP.

What is User-Agent?

The User-Agent string is a part of the HTTP header that is sent with each request to the server. It can provide details about the client’s software and hardware, like the web browser type and version, operating system, and even device types in some cases. Here, we’ll cover the basics and delve into practical PHP code to extract useful information from this string.

Getting Started: Accessing the User-Agent String in PHP

1. Access User-Agent String with $_SERVER['HTTP_USER_AGENT'] .PHP provides a global $_SERVER array which contains information such as headers, paths, and script locations. The array includes an element called 'HTTP_USER_AGENT', which you can use to access the User-Agent string directly. Here is a basic example:

<?php echo $_SERVER['HTTP_USER_AGENT']; ?>

2. Check for the Presence of User-Agent It’s a good practice to check whether the User-Agent string is set before trying to use it to avoid errors. For this purpose, you can use the isset() function:

<?php 
if (isset($_SERVER['HTTP_USER_AGENT'])) { 
   $user_agent = $_SERVER['HTTP_USER_AGENT']; 
   // Work with the User-Agent string 
} else { 
   // Handle the absence of User-Agent 
} 
?>

Understanding the User-Agent String

Before using the User-Agent string, it’s important to understand its structure. User-Agent strings can be complex as they contain a multitude of tokens that identify various aspects of the requesting client. Here’s an example of a User-Agent string:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36

This particular User-Agent string indicates that the request was made from a Chrome browser (version 58.0.3029.110) on a Windows 10 machine.

Parsing the User-Agent String

After retrieving the User-Agent string, the next step is to parse it to extract the needed information. In PHP, there are multiple ways to do this:

1. Using Built-in Functions PHP has a built-in function get_browser() which can be used to parse the User-Agent string. It requires setting up a browscap.ini file for PHP to reference. However, since this method can be memory-intensive, and maintaining the browscap.ini file up-to-date can be a burden, other more lightweight solutions are often preferred.

2. Regular Expressions You can use regular expressions to extract browser names and versions. This approach gives you precise control over what information you’re looking for:

<?php 

if (isset($_SERVER['HTTP_USER_AGENT'])) {
    // Define a regex pattern to match the browser and version
    $pattern = '/(firefox|msie|chrome|safari)[ \/](\d+)/i';

    if (preg_match($pattern, $_SERVER['HTTP_USER_AGENT'], $matches)) {
        $browser = $matches[1];
        $version = $matches[2];
        // Do something with the browser name and version
    }
}

?>

Third-Party Libraries for Parsing User-Agent

If you prefer a more straightforward approach or need to parse the User-Agent string comprehensively, numerous third-party libraries are available. Some popular libraries for handling User-Agent strings include:

  • whichbrowser/parser – A very accurate and up-to-date User-Agent string parser.
  • ua-parser/uap-php – PHP implementation of the ua-parser project, which works very well for parsing browser, engine, OS, CPU, and device types from the User-Agent string.

Libraries like these often require using Composer, PHP’s package manager, to include them in your project. Here’s how you can use ua-parser in a PHP project:


<?php
require_once 'vendor/autoload.php';
use UAParser\Parser;

$ua = $_SERVER['HTTP_USER_AGENT'];
$parser = Parser::create();
$result = $parser->parse($ua);

echo 'Browser: ' . $result->ua->family . ' ' . $result->ua->major . "\n";
echo 'Operating System: ' . $result->os->family . "\n";
echo 'Device Type: ' . ($result->device->type === null ? 'Other' : $result->device->type) . "\n";
?>

FAQs About User-Agent String

Can User-Agent be spoofed?

Yes, User-Agent strings can be spoofed, and they often are by bots and some browsers allow users to change their User-Agent string.

Is it reliable to use User-Agent string for critical features?

Because of spoofing and the variety of devices and browsers, it’s not 100% reliable to use User-Agent strings for critical feature implementation.

Are all User-Agent strings structured the same way?

No, User-Agent strings can significantly vary from browser to browser and device to device.

Conclusion

By following the methods outlined in this tutorial, developers can effectively extract and utilize the User-Agent string in PHP. While some approaches provide simple detection capabilities, others offer in-depth analysis. Choose the right one based on the needs of your PHP project.