Tuesday, 14 August 2018

How to Detect Browser Type in PHP

Check your Browser Type in PHP
Here’s an example code which can be used in PHP to detect and retrieve the web browser type as variable or used directly in comparison function.
<?php

$user_agent = $_SERVER['HTTP_USER_AGENT']; 

if (preg_match('/MSIE/i', $user_agent))
{ 
      echo "Internet Explorer";
}else{
      echo "Non-IE Browser";
} 
OR

if (strstr($user_agent,'MSIE'))
{
      echo "Internet Explorer";
} else {
      echo "Non-IE Browser";
} 
>>

Script above will detect if the visitor is using IE (Internet Explorer) browser. To code can be expanded to detect additional browser with elseif conditional tag. To check for other browser, just replace the MSIE with the user agent name for other browser. Some popular web browsers can be identified with the following string:
Internet Explorer: MSIE
Mozilla Firefox: Firefox
Google Chrome: Chrome
Apple Safari: Safari
Opera: Opera
Netscape Navigator: Netscape
Flock: Flock
Lynx: Lynx
Tip: It’s possible to use “strtolower” to make the $user_agent to all lower case so that all PHP script does not miss out on browsers which do not use standard naming convention in user agent. In this case, remember to compare against user agent string which is lower case too, such as msie, firefox and etc.

0 comments:

Post a Comment