How to differentiate Chrome and Safari - PHP
We would always like to provide our website visitors different services based their browser like Chrome Extension, Opera Add-on, Internet Explorer Tool-Bar etc.
For which we need to find what kind of browser our user is using to view our website.So how do we find it?
Its simple : we use a preg_match() function for the purpose.
It takes basically two parameters :
- The first is a search key enclosed in both "" as well as //. Example : "/chrome/"
- The second is the string in which we need to search the Key.
Following is the codes for analyzing the famous browsers; Chrome, IE, FireFox, Opera and Safari.
if(preg_match("/chrome/",strtolower($_SERVER['HTTP_USER_AGENT'])))
echo "This is Google Chrome code";
elseif(preg_match("/msie/",strtolower($_SERVER['HTTP_USER_AGENT'])))
echo "This is Internet Explorer code";
elseif(preg_match("/opera/",strtolower($_SERVER['HTTP_USER_AGENT'])))
echo "This is Opera code";
elseif(preg_match("/firefox/",strtolower($_SERVER['HTTP_USER_AGENT'])))
echo "This is FireFox code";
elseif(preg_match("/safari/",strtolower($_SERVER['HTTP_USER_AGENT'])))
echo "This is Safari code"; ?>
Now why do we need this topic at all?
When I executed this code I got a similar result for both Chrome and Safari. They are as follows :
- Chrome : Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19
- Safari : Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2
So you see there is really small difference in the output. A Chrome string is there in Chrome's output and not in Safari's.
But there is a Safari in both the outputs. Now, describe the topic we are on; Differentiate Safari from Chrome.
Use If-Else tree : Chrome's contains a "Chrome" word while Safari's not. So check if "Chrome" key is there in the $_SERVER["HTTP_USER_AGENT"], else check for the "Safari" key. While the reverse tree gives true for both the sentences and Chrome's output will not work.
Once again we solved an another problem.
Have a nice day in your website!
Comments
Post a Comment