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.