如何在 PHP 中获得用户代理

我使用这个 JS 代码来了解用户使用什么浏览器。

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

我想让这个导航器.appName 到 php 代码中,像这样使用它:

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

我该怎么做?

203332 次浏览

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

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.

You could also use the php native funcion get_browser()

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

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

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