Search code examples
phpuser-agent

how to extract on mobile device name from php user agent?


I am writing code that saves device details of the user. But when I am using PHP user agent it returns whole string of information. How do I extract only device name, for exmaple only model name like iPhone 6, Samsung Galaxy a5 etc?

I have tried some regex but that would be long code and I can't cover every single device.

I am getting

Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1

I want only iPhone OS 10_3_1


Solution

  • There are so many different ways a User Agent can be written it's hard to extract the information through just regex or simple logic. A better way would be to search for a list of given devices that you know can occur, such as from this answer, however that might make it hard to extract the version information.

    Instead I'd recommend using a third party library such as device-detector and use something in the following:

    use DeviceDetector\DeviceDetector;
    
    // Fetch the user agent
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    
    // Create an instance of DeviceDetector
    $dd = new DeviceDetector($userAgent);
    
    // Extract any information you want
    $osInfo = $dd->getOs();
    $device = $dd->getDeviceName();
    $brand = $dd->getBrandName();
    $model = $dd->getModel();