Script to detect the user's browser in PHP
Recently, for one interesting project, I needed to make a browser detection and its version in PHP. The template was responsive (responcive), and it was necessary to adjust the output of page elements for different browsers. I wrote the site on my favorite WordPress engine and the theme was designed for it. As always, without thinking twice about the task, I got into the Internet. I was surprised when I found a ready-made script, which completely satisfied me in the top ten of google issuance. Respect and respect to the developer and blogger co
who wrote this script and posted it on his blog.
What I especially liked about him, so this is the topic, that the script could detect browsers on the Gecko engine, not just major browsers (Firefox, Chrome, IE, Opera, Safari), and even those, which are built on the Trident core (Maxthon, Avant Browser, MyIE2), and even older versions of Opera, masquerading as IE. Besides, script finds and displays browser version.
The author of the blog posted some information, which I would also like to put on my site.
Theory from the words of the author:
How is browser detected in PHP?
PHP has a wonderful variable called $_SERVER[‘HTTP_USER_AGENT’].
I have, for example, she looks like this:
Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10
From here, pulling out the browser and version is simple, is not it?
Now IE 6
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)
Here it's a little more complicated., but it shouldn't cause too much trouble either..
Opera 10.61
Opera/9.80 (Windows NT 5.1; U; ru) Presto/2.6.30 Version/10.61
The opera has prepared a trick for us: browser name at the beginning, a version, how strange it is, in the end.
Safari 5.1
Mozilla/5.0 (Windows; U; Windows NT 6.1; ru-RU) AppleWebKit/533.17.8 (KHTML, like Gecko) Version/5.0.1 Safari/533.17.8
Safari surprises too: the slash is not the version number. The version number comes a little earlier.
Chrome 6.0.427.0
Mozilla/5.0 (Windows; U; Windows NT 5.1; in US) AppleWebKit/534.1 (KHTML, like Gecko) Chrome/6.0.427.0 Safari/534.1
Chrome is easier to pull out, it would be nice not to confuse it with Safari yet ...
(About, why all browsers (except Opera) call themselves Mozilla can be read in a simple and fun way In here.)
Practice from the words of the author
you already know, what variety in the line User-agent offer only five browsers.
But in 9 from 10 cases, the following regular expression will save us:
1 |
preg_match("/(MSIE|Opera|Firefox|Chrome|Version)(?:\/| )([0-9.]+)/", $agent, $browser_info); |
After that, the name of the browser will be in the second element of the array., and in the third - his version.
The only exception is Safari starting from version 3.0 and Opera starting from version 10.00.
For these browsers we write:
1 2 |
if ($browser == 'Opera' && $version == '9.80') return 'Opera '.substr($agent,-5); // возвращаем версию Оперы в конце строки if ($browser == 'Version') return 'Safari '.$version; // обозначаем браузер как Сафари |
And one more line of code:
1 |
if (!$browser && strpos($agent, 'Gecko')) return 'Browser based on Gecko'; |
If we couldn't detect the browser, but we know, that it uses the Gecko kernel, then display a message saying, that the browser is running on this kernel.
Here, in fact, and all the contents of the first, more compact function by browser definition.
Her entire code:
1 2 3 4 5 6 7 8 |
function user_min_browser($agent) { preg_match("/(MSIE|Opera|Firefox|Chrome|Version)(?:\/| )([0-9.]+)/", $agent, $browser_info); list(,$browser,$version) = $browser_info; if ($browser == 'Opera' && $version == '9.80') return 'Opera '.substr($agent,-5); if ($browser == 'Version') return 'Safari '.$version; if (!$browser && strpos($agent, 'Gecko')) return 'Browser based on Gecko'; return $browser.' '.$version; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function user_browser($agent) { preg_match("/(MSIE|Opera|Firefox|Chrome|Version|Opera Mini|Netscape|Konqueror|SeaMonkey|Camino|Minefield|Iceweasel|K-Meleon|Maxthon)(?:\/| )([0-9.]+)/", $agent, $browser_info); // регулярное выражение, которое позволяет отпределить 90% браузеров list(,$browser,$version) = $browser_info; // получаем данные из массива в переменную if (preg_match("/Opera ([0-9.]+)/i", $agent, $opera)) return 'Opera '.$opera[1]; // определение _очень_старых_ версий Оперы (до 8.50), при желании можно убрать if ($browser == 'MSIE') { // если браузер определён как IE preg_match("/(Maxthon|Avant Browser|MyIE2)/i", $agent, $ie); // проверяем, не разработка ли это на основе IE if ($ie) return $ie[1].' based on IE '.$version; // если да, то возвращаем сообщение об этом return 'IE '.$version; // иначе просто возвращаем IE и номер версии } if ($browser == 'Firefox') { // если браузер определён как Firefox preg_match("/(Flock|Navigator|Epiphany)\/([0-9.]+)/", $agent, $ff); // проверяем, не разработка ли это на основе Firefox if ($ff) return $ff[1].' '.$ff[2]; // если да, то выводим номер и версию } if ($browser == 'Opera' && $version == '9.80') return 'Opera '.substr($agent,-5); // если браузер определён как Opera 9.80, берём версию Оперы из конца строки if ($browser == 'Version') return 'Safari '.$version; // определяем Сафари if (!$browser && strpos($agent, 'Gecko')) return 'Browser based on Gecko'; // для неопознанных браузеров проверяем, если они на движке Gecko, и возращаем сообщение об этом return $browser.' '.$version; // для всех остальных возвращаем браузер и версию } |
Work examples
The table shows the result of the work of two functions - in the first column, the browser, in which the functions were called, in the second - the response of the function, taking into account little-known browsers, in the third - the result of the reduced function.
Browser | The result of the full function | Result of shorthand function |
Firefox 1.5.0.12 | Firefox 1.5.0.12 | Firefox 1.5.0.12 |
Firefox 3.0.10 | Firefox 3.0.10 | Firefox 3.0.10 |
Firefox 3.6.9 | Firefox 3.6.9 | Firefox 3.6.9 |
Firefox 4.0 | Firefox 4.0 | Firefox 4.0 |
IE 4.01 | IE 4.01 | MSIE 4.01 |
IE 5.5 | IE 5.5 | MSIE 5.5 |
IE 6.0 | IE 6.0 | MSIE 6.0 |
IE 7.0 | IE 7.0 | MSIE 7.0 |
IE 8.0 | IE 8.0 | MSIE 8.0 |
Chrome 5.0.375.127 | Chrome 5.0.375.127 | Chrome 5.0.375.127 |
Chromium 6.0.472.36 | Chrome 6.0.472.36 | Chrome 6.0.472.36 |
Chrome 7.0.517.8 | Chrome 7.0.517.8 | Chrome 7.0.517.8 |
Opera 7.03 | Opera 7.03 | MSIE 6.0 |
Opera 8.0 | Opera 8.0 | MSIE 6.0 |
Opera 8.54 | Opera 8.54 | Opera 8.54 |
Opera 9.50 | Opera 9.50 | Opera 9.50 |
Opera 10.00 | Opera 10.00 | Opera 10.00 |
Opera 10.10 | Opera 10.10 | Opera 10.10 |
Opera 10.61 | Opera 10.61 | Opera 10.61 |
Safari 3.0 | Safari 3.0 | Safari 3.0 |
Safari 4.0 | Safari 4.0 | Safari 4.0 |
Safari 5.0.1 | Safari 5.0.1 | Safari 5.0.1 |
Flock 1.2.6 | Flock 1.2.6 | Firefox 2.0.0.17 |
Epiphany 2.22 | Epiphany 2.22 | Firefox 2.0.0.20 |
Navigator 9.0.0.6 | Navigator 9.0.0.6 | Firefox 2.0.0.12 |
Netscape 8.1.3 | Netscape 8.1.3 | Browser based on Gecko |
Konqueror 4.4 | Konqueror 4.4 | Browser based on Gecko |
Galleon 2.0.4 | Browser based on Gecko | Browser based on Gecko |
Iceape 1.1.13 | Browser based on Gecko | Browser based on Gecko |
Iceweasel 3.0.4 | Iceweasel 3.0.4 | Browser based on Gecko |
SeaMonkey 1.1.14 | SeaMonkey 1.1.14 | Browser based on Gecko |
Minefield 3.7 | Minefield 3.7 | Browser based on Gecko |
Avant Browser 7.0 | Avant Browser based on IE 7.0 | MSIE 7.0 |
Camino 2.0.4 | Camino 2.0.4 | Firefox 3.0.19 |
Browsers marked in red, which the function could not determine.
And here you can check the functionality of the functions in your browser.
Hope, that these functions will be useful to someone.
Good luck.
You can download the browser detection script from me:
or on the author's website:
https://www.recens.ru/php/detect_user_browser.html
Once again, special thanks to the author!
Defining mobile browsers
I also found from the comments on the author's website, how to identify mobile devices:
1 2 3 4 5 6 7 8 9 10 11 |
function device() { $user_agent = $this->agent(); // взять USER_AGENT пользователя $oses = array ('Windows 95','Win95','Windows_95', 'Windows 98', 'Win98', 'Windows NT', 'winNT', 'Windows 2000', 'Windows XP', 'winXP', 'Windows ME', 'winME', 'OpenBSD', 'SunOS', 'Linux', 'Mac_PowerPC', 'Macintosh', 'QNX', 'BeOS', 'OS/2'); foreach($oses as $os) { if (substr_count($user_agent, $os) > 0) return 'PC'; } return 'Mobile'; } |
returns mobile or PC, good luck )
/*
- Basic web design course;
- Site layout;
- General course on CMS WordPress and continuation of the course on template development;
- Website development in PHP.