108

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?

1

5 Answers 5

284

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

6
  • 14
    Pay attention, this can be not set! Oct 18, 2016 at 18:19
  • 20
    In PHP7+, you can write $_SERVER['HTTP_USER_AGENT']??null to have it return null instead of throw an error when it isn't defined Aug 30, 2017 at 16:29
  • Or do this, if you just want to do string manipulations later and do not want to care about null or not set: $ua = $_SERVER['HTTP_USER_AGENT'].''; Aug 31, 2017 at 11:47
  • 32
    Or simply check with isset()... Clean and readable code should always be a high priority.
    – StanE
    Nov 2, 2017 at 18:59
  • 3
    @StanE - The PHP 7 version is perfectly fine. Novel !== Unreadable. Jun 9, 2021 at 8:57
8

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";
}
1
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.

1
  • 1
    is this working $_SERVER['USER_AGENT']?? Should be $_SERVER['HTTP_USER_AGENT']???
    – jogesh_pi
    Apr 20, 2012 at 9:54
6

You could also use the php native funcion get_browser()

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

4
  • 4
    This requires you to have an up-to-date browscap.ini file Mar 19, 2019 at 19:07
  • 1
    it does and there are quite a few online resources where you can download one for your site, such as browscap.org
    – Aurovrata
    Mar 20, 2019 at 6:54
  • 1
    return null or false Dec 27, 2019 at 0:27
  • 2
    make sure you have a browscap.ini file
    – Aurovrata
    Dec 27, 2019 at 7:54
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'   ){
       //        
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.