Search code examples
phpandroidcompatibilityandroid-browser

Detecting the stock android browser with PHP?


As many of you might have encountered, the stock Android browser, thankfully discontinued in Android 4.4 is more or less the modern IE6 - riddled with bugs and broken to the point of inciting suicide amongst developers. Consequently, the need to serve resources specific to that browser is quickly becoming a necessity, and the best way to do that would be by linking stylesheets/js through the back end. So what's a fool proof way of detecting the browser using PHP?


Solution

  • Thankfully it's pretty simple:

    //get the user agent string
    $ua = $_SERVER['HTTP_USER_AGENT'];
    
    //results array
    $matches = [];
    
    //perform regex query
    preg_match ( '/Android.*AppleWebKit\/([\d.]+)/', $ua, $matches);
    
    //Check if the regex query returned matches specific to 
    //the android stock browser.
    if( isset($matches[0]) && 
    
      //This is where we diffrentiate the stock browser from chrome, 
      //the default browser's webkit version never goes above 537
      ( isset($matches[1]) && intval($matches[1] < 537) ) ){
        echo 'Browsing via stock android browser';
    }
    

    Please add your improved answers.