Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect the browser with PHP or JavaScript?

Tags:

javascript

php

How can I detect if the user is not using any of the browsers Chrome, Firefox or Internet Explorer using JavaScript or PHP?

like image 668
Web Worm Avatar asked Dec 13 '09 06:12

Web Worm


2 Answers

The best way to do this in JS I found is on Quirksmode. I made one for PHP which should work with common browsers :

  $browser = array(
    'version'   => '0.0.0',
    'majorver'  => 0,
    'minorver'  => 0,
    'build'     => 0,
    'name'      => 'unknown',
    'useragent' => ''
  );

  $browsers = array(
    'firefox', 'msie', 'opera', 'chrome', 'safari', 'mozilla', 'seamonkey', 'konqueror', 'netscape',
    'gecko', 'navigator', 'mosaic', 'lynx', 'amaya', 'omniweb', 'avant', 'camino', 'flock', 'aol'
  );

  if (isset($_SERVER['HTTP_USER_AGENT'])) {
    $browser['useragent'] = $_SERVER['HTTP_USER_AGENT'];
    $user_agent = strtolower($browser['useragent']);
    foreach($browsers as $_browser) {
      if (preg_match("/($_browser)[\/ ]?([0-9.]*)/", $user_agent, $match)) {
        $browser['name'] = $match[1];
        $browser['version'] = $match[2];
        @list($browser['majorver'], $browser['minorver'], $browser['build']) = explode('.', $browser['version']);
        break;
      }
    }
  }
like image 94
Fabien Ménager Avatar answered Sep 21 '22 14:09

Fabien Ménager


Here is JavaScript code through which you can easily detect the browser.

    var userAgent = navigator.userAgent.toLowerCase();

    // Figure out what browser is being used.
    var Browser = {
        Version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
        Chrome: /chrome/.test(userAgent),
        Safari: /webkit/.test(userAgent),
        Opera: /opera/.test(userAgent),
        IE: /msie/.test(userAgent) && !/opera/.test(userAgent),
        Mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent),
        Check: function() { alert(userAgent); }
    };

    if (Browser.Chrome || Browser.Mozilla) {
        // Do your stuff for Firefox and Chrome.
    }
    else if (Browser.IE) {
        // Do something related to Internet Explorer.
    }
    else {
        // The browser is Safari, Opera or some other.
    }
like image 39
Zain Shaikh Avatar answered Sep 20 '22 14:09

Zain Shaikh