Current Location: Home> Latest Articles> How to encapsulate an enhanced version of the get_client_version tool class

How to encapsulate an enhanced version of the get_client_version tool class

gitbox 1970-01-01

In web development, obtaining client version information (such as browser, operating system, device type, etc.) is a common requirement. Whether used for statistical analysis, functional compatibility judgment, or personalized display, accurately identifying the client environment can significantly improve the user experience.

PHP's own $_SERVER['HTTP_USER_AGENT'] provides basic client information, but parsing it is not easy. In order to make this task more efficient and convenient, we can encapsulate a more powerful get_client_version function tool class to automatically identify browsers, operating systems, device types and even APP versions.

1. Why do packaging need to be done?

Directly using the original User-Agent string has the following pain points:

  • String format is not unified, parsing rules are complicated

  • The browser and operating system versions are updated frequently, and the recognition method is often invalid

  • Lack of flexibility and scalability, it is difficult to cope with multi-terminal application needs

To overcome these problems, we need a structured, modular, and extensible tool class.

2. Tool design ideas

We plan to create a ClientVersionHelper class with the following capabilities:

  • Automatically identify browser types and versions (Chrome, Firefox, Safari, etc.)

  • Automatically identify the operating system and version (Windows, macOS, Linux, Android, iOS)

  • Determine whether it is a mobile device

  • Supports custom application version header recognition (such as the UA format of self-developed apps)

  • Provide a unified structured return format

3. Code implementation

The following is a basic implementation, which you can further expand according to project requirements in the future:

 <?php

class ClientVersionHelper
{
    protected $userAgent;

    public function __construct($userAgent = null)
    {
        $this->userAgent = $userAgent ?: ($_SERVER['HTTP_USER_AGENT'] ?? '');
    }

    public function getClientInfo()
    {
        return [
            'browser' => $this->getBrowser(),
            'os'      => $this->getOS(),
            'device'  => $this->isMobile() ? 'Mobile' : 'Desktop',
            'raw'     => $this->userAgent,
        ];
    }

    protected function getBrowser()
    {
        $ua = $this->userAgent;

        if (preg_match('/Chrome\/([0-9\.]+)/i', $ua, $matches)) {
            return 'Chrome ' . $matches[1];
        }

        if (preg_match('/Firefox\/([0-9\.]+)/i', $ua, $matches)) {
            return 'Firefox ' . $matches[1];
        }

        if (preg_match('/Safari\/([0-9\.]+)/i', $ua) && !preg_match('/Chrome/i', $ua)) {
            return 'Safari';
        }

        if (preg_match('/MSIE ([0-9\.]+)/i', $ua, $matches)) {
            return 'Internet Explorer ' . $matches[1];
        }

        return 'Unknown';
    }

    protected function getOS()
    {
        $ua = $this->userAgent;

        if (preg_match('/Windows NT ([0-9\.]+)/i', $ua, $matches)) {
            return 'Windows ' . $matches[1];
        }

        if (preg_match('/Mac OS X ([0-9_\.]+)/i', $ua, $matches)) {
            return 'macOS ' . str_replace('_', '.', $matches[1]);
        }

        if (preg_match('/Android ([0-9\.]+)/i', $ua, $matches)) {
            return 'Android ' . $matches[1];
        }

        if (preg_match('/iPhone OS ([0-9_]+)/i', $ua, $matches)) {
            return 'iOS ' . str_replace('_', '.', $matches[1]);
        }

        if (preg_match('/Linux/i', $ua)) {
            return 'Linux';
        }

        return 'Unknown';
    }

    protected function isMobile()
    {
        return preg_match('/Mobile|Android|iPhone|iPad/i', $this->userAgent);
    }
}

4. Use examples

Structured client version information is obtained with just a simple call:

 $clientHelper = new ClientVersionHelper();
$info = $clientHelper->getClientInfo();

echo '<pre>';
print_r($info);
echo '</pre>';

The example of the return result is as follows:

 Array
(
    [browser] => Chrome 120.0.0.0
    [os] => Windows 10.0
    [device] => Desktop
    [raw] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ...
)

5. Expansion direction suggestions

You can add the following extensions to the existing basis:

  • Add support for custom UA identifiers, such as MyApp/3.4.5 in your own app UA

  • Integrate UA databases (such as https://gitbox.net/ua-database ) to support more device recognition

  • Provide a caching mechanism to improve processing efficiency

  • Encapsulate this class into a Composer package for easy reuse and update

6. Conclusion

Encapsulating an efficient get_client_version tool class can not only greatly simplify the code logic recognized by the client, but also make your application more maintainable and scalable. Instead of manually parsing the User-Agent every time, it is better to leave it to a powerful and reliable tool class to handle it.

With the increasing number of device and browser types, a good package will keep your project at the forefront of user recognition.