How to get user agent in PHP

PhpUser Agent

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

You could also use the php native funcion get_browser()

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

Solution 3 - Php

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.

Solution 4 - Php

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

Solution 5 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOlga BudnikView Question on Stackoverflow
Solution 1 - PhpnoliView Answer on Stackoverflow
Solution 2 - PhpAurovrataView Answer on Stackoverflow
Solution 3 - Phparthur86View Answer on Stackoverflow
Solution 4 - PhpDEEView Answer on Stackoverflow
Solution 5 - PhpSalemView Answer on Stackoverflow