Olga Budnik
Olga Budnik

Reputation: 1223

How to get user agent in PHP

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?

Upvotes: 114

Views: 254849

Answers (5)

Salem
Salem

Reputation: 784

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'   ){
       //        
    }

Upvotes: 2

DEE
DEE

Reputation: 81

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

Upvotes: 8

Aurovrata
Aurovrata

Reputation: 2289

You could also use the php native funcion get_browser()

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

Upvotes: 6

arthur86
arthur86

Reputation: 531

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.

Upvotes: 6

noli
noli

Reputation: 3745

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

Upvotes: 297

Related Questions