To get the user agent in php, you can use the $_SERVER super global variable and access the key ‘HTTP_USER_AGENT’.
$user_agent = $_SERVER['HTTP_USER_AGENT'];
The User-Agent request header is a string that lets servers and network peers identify various information like the application, operating system, vendor, and/or version of the requesting user agent.
When building web pages in php, sometimes it can be useful to know the user agent so we can provide certain information to the user.
To get the user agent in php, you can use the $_SERVER super global variable and access the key ‘HTTP_USER_AGENT’.
$user_agent = $_SERVER['HTTP_USER_AGENT'];
How to Get the Browser from the User Agent in php
The user agent variable usually is messy and doesn’t provide us a lot of value until we parse it for certain information.
One example of how to use the user agent is to determine which browser the user is accessing your web page from.
Below is a simple function (found on stack overflow), which will help you get the browser from the user agent variable in php.
if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE)
echo 'Internet Explorer';
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Trident') !== FALSE) //For Supporting IE 11
echo 'Internet Explorer';
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') !== FALSE)
echo 'Mozilla Firefox';
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== FALSE)
echo 'Google Chrome';
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== FALSE)
echo "Opera Mini";
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== FALSE)
echo "Opera";
elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== FALSE)
echo "Safari";
else
echo 'Something else';
Hopefully this article has been useful for you to use php to get the user agent.
That function from stackoverflow is faulty and will show “Chrome” as result in many cases, since Chrome is almost always available in any user string.
The check has to happen in the right order. less known browsers should be checked first, and Chrome and Safari should be checked at last to make sure all other browsers have been checked before.
I find this function everywhere on the web and it’s surprising no one noticed this “bug”.
Also, the function can be written in 3-4 lines instead of all of those if/else’s you have been using.
Simply put the checks in a foreach loop which fetches data from your database.