Detecting Browser with PHP

Howdy Peps!

Here’s a short snippet that detects your browser agent

//—-Snippet Starts here—–//


<!--?php
1. $ua = $_SERVER["HTTP_USER_AGENT"];

  1. $browser = strpos($ua, ‘Chrome’) ? true : false;

  2. if($browser == true)

  3. {
  4. echo “Chrome”;
  5. }

  6. // new con

  7. else
  8. {
  9. if ($ua = $_SERVER[“HTTP_USER_AGENT”])
  10. $browser = strpos($ua, ‘IE’) ? true : false;
  11. if($browser == true)
  12. {
  13. echo “IE”;
  14. }

//—-Snippet Ends here—–//

 

Description : The above code snippets detects the browser weather it’s Chrome or IE, the

Line#2 fetches data from $ua and read from the variable then later compares if the detected browser is either chrome or not if it turns out true the code continues else jumps on the else block onto line #8

The $_SERVER[“HTTP_USER_AGENT”]; renders the browser’s agent that you are browsing with while executing the code.

The $browser = strpos($ua, ‘Chrome’) ? true : false; containts 2 parameters that is (UserAgent, String to be matched with)

The Strpos() function finds the numeric position of the first occurrence of needle in the haystack string.
in our case needle is $ua and haystack is the string (browser name).

I used this snippet to loosely forbid my website to execute on certain browsers, well you can use it on whatever you want, like this snippet that returns the browser name

// –Snippet Starts –//

<?php
$ua = $_SERVER[“HTTP_USER_AGENT”];

$browser = strpos($ua, ‘Chrome’) ? true : false;

if($browser == true)
{
echo “Chrome”;
}

// new con
else
{
if ($ua = $_SERVER[“HTTP_USER_AGENT”])
$browser = strpos($ua, ‘IE’) ? true : false;
if($browser == true)
{
echo “IE”;
}
else
{
if ($ua = $_SERVER[“HTTP_USER_AGENT”])
{
$browser = strpos($ua, ‘Firefox’) ? true : false;
if($browser == ‘Firefox’)
{
echo “Mozilla”;
}

else
{
if ($ua = $_SERVER[“HTTP_USER_AGENT”])
{
$browser = strpos($ua, ‘Safari’) ? true : false;
if($browser == true)
{
echo “Safari”;
}
else
{echo “other”;}

}
}
}
}
}

?>
//–Snippet Ends–//

Have Fun 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s