106

I'm using this JS code to know what browser is user using for.

<script>
  document.write(navigator.appName);
</script>

And I want to get this navigator.appName to php code to use it like this:

if ($appName == "Internet Explorer") {
  // blabla
}

How can I do it?

Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115
Olga Budnik
  • 1,143
  • 2
  • 8
  • 10
  • Related: [reliable user browser detection with php](https://stackoverflow.com/questions/2257597/reliable-user-browser-detection-with-php). – showdev Mar 17 '20 at 10:14

5 Answers5

276

Use the native PHP $_SERVER['HTTP_USER_AGENT'] variable instead.

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
noli
  • 3,535
  • 3
  • 18
  • 20
6

You can use the jQuery ajax method link if you want to pass data from client to server. In this case you can use $_SERVER['HTTP_USER_AGENT'] variable to found browser user agent.

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
arthur86
  • 531
  • 1
  • 3
  • 20
6

You could also use the php native funcion get_browser()

IMPORTANT NOTE: You should have a browscap.ini file.

Dan Linh
  • 129
  • 1
  • 7
Aurovrata
  • 2,000
  • 27
  • 45
6

I use:

<?php
$agent = $_SERVER["HTTP_USER_AGENT"];

if( preg_match('/MSIE (\d+\.\d+);/', $agent) ) {
  echo "You're using Internet Explorer";
} else if (preg_match('/Chrome[\/\s](\d+\.\d+)/', $agent) ) {
  echo "You're using Chrome";
} else if (preg_match('/Edge\/\d+/', $agent) ) {
  echo "You're using Edge";
} else if ( preg_match('/Firefox[\/\s](\d+\.\d+)/', $agent) ) {
  echo "You're using Firefox";
} else if ( preg_match('/OPR[\/\s](\d+\.\d+)/', $agent) ) {
  echo "You're using Opera";
} else if (preg_match('/Safari[\/\s](\d+\.\d+)/', $agent) ) {
  echo "You're using Safari";
}
DEE
  • 61
  • 1
  • 2
2

PHP 8 have this features $_SERVER['HTTP_SEC_CH_UA'] Sec-CH-UA let's you detect the browser name directly

if (  strpos ( $_SERVER['HTTP_SEC_CH_UA'],'Opera'   ){
       //        
    }
Salem
  • 654
  • 7
  • 24