Thursday, 28 February 2013

PHP coding for finding browser and OS platform

Source Code:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Simple coding for finding web browser and OS Paltform</title>
</head>
<?php
   $viewer = getenv( "HTTP_USER_AGENT" );
   $browser = "An unidentified browser";
   if( preg_match( "/MSIE/i", "$viewer" ) )
   {
      $browser = "Internet Explorer";
   }
   else if(  preg_match( "/Netscape/i", "$viewer" ) )
   {
      $browser = "Netscape";
   }
   else if(  preg_match( "/Mozilla/i", "$viewer" ) )
   {
      $browser = "Mozilla";
   }
   $platform = "An unidentified OS!";
   if( preg_match( "/Windows/i", "$viewer" ) )
   {
      $platform = "Windows!";
   }
   else if ( preg_match( "/Linux/i", "$viewer" ) )
   {
      $platform = "Linux!";
   }
   echo("You are using $browser on $platform");
?>
<body>
</body>
</html>

DEMO OUTPUT IS :

You are using Mozilla on Windows!

2 comments:

  1. Very Useful code snippet
    but can we use strstr function instead of preg_match since execution time for processing string through regular expressions will be overhead
    and strstr function will just match pattern of strings
    Looking forward for your reply

    ReplyDelete
  2. Checking if a device is a mobile device is even more interesting. Identifying tablet devices can become quite tricky using user agent strings.

    ReplyDelete