Detecting browsers of iPhone, iPod, iPad, Android and BlackBerry with JavaScript and PHP
To begin with, we need to understand that in the HTTP protocol, browser send its identity called user agent to the server to request the wanted webpage. Every browser has its only unique user agent value, and therefore we can check that value to identify the user browser. So, first we have to take a look at some examples of user agents of mobile devices.
iPhone user agent
[sourcecode]
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3
[/sourcecode]
iPod Touch user agent
[sourcecode]
Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A101a Safari/419.3
[/sourcecode]
iPad user agent
[sourcecode]
Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10
[/sourcecode]
Android user agent
[sourcecode]
Mozilla/5.0 (Linux; U; Android 1.1; en-gb; dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2
Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17
[/sourcecode]
BlackBerry user agent
[sourcecode]
BlackBerry9000/4.6.0.266 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/120
[/sourcecode]
After all, in programming, we gather these data to do the checking. First in JavaScript:
[sourcecode language=”javascript”]
if (/(iPhone|iPod|iPad)/.test(navigator.userAgent)) <
/* This is iOS */
>
if (/Android/.test(navigator.userAgent)) <
/* This is Android */
>
if (/BlackBerry)/.test(navigator.userAgent)) <
/* This is BlackBerry */
>
if (/(iPhone|iPod|iPad|BlackBerry|Android)/.test(navigator.userAgent)) <
/* This is one of the mentioned mobile device browsers */
>
[/sourcecode]
And this is how it works in PHP:
[sourcecode language=”php”]
if (preg_match(‘/iPhone|iPod|iPad/’, $_SERVER[‘HTTP_USER_AGENT’])) <
/* This is iOS */
>
if (preg_match(‘/Android/’, $_SERVER[‘HTTP_USER_AGENT’])) <
/* This is Android */
>
if (preg_match(‘/BlackBerry/’, $_SERVER[‘HTTP_USER_AGENT’])) <
/* This is BlackBerry */
>
if (preg_match(‘/iPhone|iPod|iPad|BlackBerry|Android/’, $_SERVER[‘HTTP_USER_AGENT’])) <
/* This is one of the mentioned mobile device browsers */
>
[/sourcecode]
Источник
get_browser
(PHP 4, PHP 5, PHP 7, PHP 8)
get_browser — Сообщает о возможностях браузера пользователя
Описание
Пытается определить возможности браузера пользователя, производя поиск информации о браузере в файле browscap.ini .
Список параметров
Анализируемая строка с User Agent. По умолчанию используется значение HTTP User-Agent. Тем не менее, этот параметр можно пропустить для получения дополнительной информации о браузере.
Параметр может быть пропущен, если его значение будет равно null .
Если равен true , то функция вернёт массив ( array ) вместо объекта ( object ).
Возвращаемые значения
Информация возвращается в виде объекта, либо в виде массива, который содержит различные данные, к примеру, мажорную и минорную версию браузера и строку ID; значения с true / false для таких функций браузера, таких как фреймы, JavaScript, cookies и т.д.
Наличие cookies означает, что браузер имеет возможность приёма cookies, а не сообщает о том, включил ли пользователь возможность приёма cookies или нет. Единственным способом проверки возможности браузера принимать cookies является установка cookie с помощью setcookie() , обновление страницы и проверка значения.
Возвращает false , если невозможно получить информацию, например, когда параметр конфигурации browscap в php.ini не был установлен.
Примеры
Пример #1 Вывод информации о браузере пользователя
echo $_SERVER [ ‘HTTP_USER_AGENT’ ] . «\n\n» ;
$browser = get_browser ( null , true );
print_r ( $browser );
?>
Результатом выполнения данного примера будет что-то подобное:
Примечания
Для работы этой функции необходимо, чтобы в установке browscap в настройках php.ini был установлен корректный путь к файлу browscap.ini в вашей системе.
browscap.ini не поставляется с PHP, но вы можете последнюю его версию здесь: » php_browscap.ini.
browscap.ini содержит информацию о большинстве браузеров, он требует обновлений для поддержания его базы актуальной Формат файла довольно очевиден.
User Contributed Notes 16 notes
As of PHP 7.0.15 and 7.1.1 and higher, get_browser() now performs much better — reportedly 100x faster. The Changelog, bug description, and solution are here:
This function is too slow for todays needs.
If you need browser / device / operating system detection, please try one of listed packages here: https://github.com/ThaDafinser/UserAgentParser
Since browser detection can be tricky and very slow, I compared a few packages.
Here are the results:
User Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36
Sinergi Package
—————
Chrome 63.0.3239.84 on Windows 10.0
Took 0.0022480487823486 seconds.
—————
WhichBrowser Package
—————
Chrome 63 on Windows 10
Took 0.021045207977295 seconds.
—————
Piwik Package
—————
Chrome 63.0 on Windows 10
Took 0.079447031021118 seconds.
—————
get_browser Package
—————
Chrome 63.0 on Windows 10
Took 0.09611701965332 seconds.
—————
User Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0
Sinergi Package
—————
Firefox 57.0 on Windows 10.0
Took 0.0023159980773926 seconds.
—————
WhichBrowser Package
—————
Firefox 57.0 on Windows 10
Took 0.019663095474243 seconds.
—————
Piwik Package
—————
Firefox 57.0 on Windows 10
Took 0.079678058624268 seconds.
—————
get_browser Package
—————
Firefox 57.0 on Windows 10
Took 0.02236008644104 seconds.
—————
The consistent winner (by speed, not necessarily coverage) by far is:
https://github.com/sinergi/php-browser-detector
To my surprise I found that none of the get_browser alternatives output the correct name / version combination that I was looking for using Opera or Chrome. They either give the wrong name eg Safari when in fact it should be Chrome and if the ua string includes a version number as with the latest versions of Chrome and Opera the wrong number is reported. So I took bits and pieces from the various examples and combined them and added a check for version.
function getBrowser ()
<
$u_agent = $_SERVER [ ‘HTTP_USER_AGENT’ ];
$bname = ‘Unknown’ ;
$platform = ‘Unknown’ ;
$version = «» ;
//First get the platform?
if ( preg_match ( ‘/linux/i’ , $u_agent )) <
$platform = ‘linux’ ;
>
elseif ( preg_match ( ‘/macintosh|mac os x/i’ , $u_agent )) <
$platform = ‘mac’ ;
>
elseif ( preg_match ( ‘/windows|win32/i’ , $u_agent )) <
$platform = ‘windows’ ;
>
// Next get the name of the useragent yes seperately and for good reason
if( preg_match ( ‘/MSIE/i’ , $u_agent ) && ! preg_match ( ‘/Opera/i’ , $u_agent ))
<
$bname = ‘Internet Explorer’ ;
$ub = «MSIE» ;
>
elseif( preg_match ( ‘/Firefox/i’ , $u_agent ))
<
$bname = ‘Mozilla Firefox’ ;
$ub = «Firefox» ;
>
elseif( preg_match ( ‘/Chrome/i’ , $u_agent ))
<
$bname = ‘Google Chrome’ ;
$ub = «Chrome» ;
>
elseif( preg_match ( ‘/Safari/i’ , $u_agent ))
<
$bname = ‘Apple Safari’ ;
$ub = «Safari» ;
>
elseif( preg_match ( ‘/Opera/i’ , $u_agent ))
<
$bname = ‘Opera’ ;
$ub = «Opera» ;
>
elseif( preg_match ( ‘/Netscape/i’ , $u_agent ))
<
$bname = ‘Netscape’ ;
$ub = «Netscape» ;
>
// finally get the correct version number
$known = array( ‘Version’ , $ub , ‘other’ );
$pattern = ‘#(?
‘ . join ( ‘|’ , $known ) .
‘)[/ ]+(? [0-9.|a-zA-Z.]*)#’ ;
if (! preg_match_all ( $pattern , $u_agent , $matches )) <
// we have no matching number just continue
>
// see how many we have
$i = count ( $matches [ ‘browser’ ]);
if ( $i != 1 ) <
//we will have two since we are not using ‘other’ argument yet
//see if version is before or after the name
if ( strripos ( $u_agent , «Version» ) strripos ( $u_agent , $ub )) <
$version = $matches [ ‘version’ ][ 0 ];
>
else <
$version = $matches [ ‘version’ ][ 1 ];
>
>
else <
$version = $matches [ ‘version’ ][ 0 ];
>
// check if we have a number
if ( $version == null || $version == «» )
return array(
‘userAgent’ => $u_agent ,
‘name’ => $bname ,
‘version’ => $version ,
‘platform’ => $platform ,
‘pattern’ => $pattern
);
>
// now try it
$ua = getBrowser ();
$yourbrowser = «Your browser: » . $ua [ ‘name’ ] . » » . $ua [ ‘version’ ] . » on » . $ua [ ‘platform’ ] . » reports:
» . $ua [ ‘userAgent’ ];
print_r ( $yourbrowser );
?>
If you ONLY need a very fast and simple function to detect the browser name (update to May 2016):
function get_browser_name ( $user_agent )
<
if ( strpos ( $user_agent , ‘Opera’ ) || strpos ( $user_agent , ‘OPR/’ )) return ‘Opera’ ;
elseif ( strpos ( $user_agent , ‘Edge’ )) return ‘Edge’ ;
elseif ( strpos ( $user_agent , ‘Chrome’ )) return ‘Chrome’ ;
elseif ( strpos ( $user_agent , ‘Safari’ )) return ‘Safari’ ;
elseif ( strpos ( $user_agent , ‘Firefox’ )) return ‘Firefox’ ;
elseif ( strpos ( $user_agent , ‘MSIE’ ) || strpos ( $user_agent , ‘Trident/7’ )) return ‘Internet Explorer’ ;
echo get_browser_name ( $_SERVER [ ‘HTTP_USER_AGENT’ ]);
?>
This function also resolves the trouble with Edge (that contains in the user agent the string «Safari» and «Chrome»), with Chrome (contains the string «Safari») and IE11 (that do not contains ‘MSIE’ like all other IE versions).
Note that «strpos» is the fastest function to check a string (far better than «preg_match») and Opera + Edge + Chrome + Safari + Firefox + Internet Explorer are the most used browsers today (over 97%).
Follow up to Francesco R’s post from 2016.
His function works for most human traffic; added a few lines to cover the most common bot traffic. Also fixed issue with function failing to detect strings at position 0 due to strpos behavior.
// Function written and tested December, 2018
function get_browser_name ( $user_agent )
<
// Make case insensitive.
$t = strtolower ( $user_agent );
// If the string *starts* with the string, strpos returns 0 (i.e., FALSE). Do a ghetto hack and start with a space.
// «[strpos()] may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.»
// http://php.net/manual/en/function.strpos.php
$t = » » . $t ;
// Humans / Regular Users
if ( strpos ( $t , ‘opera’ ) || strpos ( $t , ‘opr/’ ) ) return ‘Opera’ ;
elseif ( strpos ( $t , ‘edge’ ) ) return ‘Edge’ ;
elseif ( strpos ( $t , ‘chrome’ ) ) return ‘Chrome’ ;
elseif ( strpos ( $t , ‘safari’ ) ) return ‘Safari’ ;
elseif ( strpos ( $t , ‘firefox’ ) ) return ‘Firefox’ ;
elseif ( strpos ( $t , ‘msie’ ) || strpos ( $t , ‘trident/7’ )) return ‘Internet Explorer’ ;
// Search Engines
elseif ( strpos ( $t , ‘google’ ) ) return ‘[Bot] Googlebot’ ;
elseif ( strpos ( $t , ‘bing’ ) ) return ‘[Bot] Bingbot’ ;
elseif ( strpos ( $t , ‘slurp’ ) ) return ‘[Bot] Yahoo! Slurp’ ;
elseif ( strpos ( $t , ‘duckduckgo’ ) ) return ‘[Bot] DuckDuckBot’ ;
elseif ( strpos ( $t , ‘baidu’ ) ) return ‘[Bot] Baidu’ ;
elseif ( strpos ( $t , ‘yandex’ ) ) return ‘[Bot] Yandex’ ;
elseif ( strpos ( $t , ‘sogou’ ) ) return ‘[Bot] Sogou’ ;
elseif ( strpos ( $t , ‘exabot’ ) ) return ‘[Bot] Exabot’ ;
elseif ( strpos ( $t , ‘msn’ ) ) return ‘[Bot] MSN’ ;
// Common Tools and Bots
elseif ( strpos ( $t , ‘mj12bot’ ) ) return ‘[Bot] Majestic’ ;
elseif ( strpos ( $t , ‘ahrefs’ ) ) return ‘[Bot] Ahrefs’ ;
elseif ( strpos ( $t , ‘semrush’ ) ) return ‘[Bot] SEMRush’ ;
elseif ( strpos ( $t , ‘rogerbot’ ) || strpos ( $t , ‘dotbot’ ) ) return ‘[Bot] Moz or OpenSiteExplorer’ ;
elseif ( strpos ( $t , ‘frog’ ) || strpos ( $t , ‘screaming’ )) return ‘[Bot] Screaming Frog’ ;
// Miscellaneous
elseif ( strpos ( $t , ‘facebook’ ) ) return ‘[Bot] Facebook’ ;
elseif ( strpos ( $t , ‘pinterest’ ) ) return ‘[Bot] Pinterest’ ;
// Check for strings commonly used in bot user agents
elseif ( strpos ( $t , ‘crawler’ ) || strpos ( $t , ‘api’ ) ||
strpos ( $t , ‘spider’ ) || strpos ( $t , ‘http’ ) ||
strpos ( $t , ‘bot’ ) || strpos ( $t , ‘archive’ ) ||
strpos ( $t , ‘info’ ) || strpos ( $t , ‘data’ ) ) return ‘[Bot] Other’ ;
Источник
Php if android browser
Helps detect the user’s browser and platform at the PHP level via the user agent
You can add this library as a local, per-project dependency to your project using Composer:
If you only need this library during development, for instance to run your project’s test suite, then you should add it as a development-time dependency:
This solution identifies the following Browsers and does a best-guess on the version:
- Opera ( Browser::BROWSER_OPERA )
- WebTV ( Browser::BROWSER_WEBTV )
- NetPositive ( Browser::BROWSER_NETPOSITIVE )
- Edge ( Browser::BROWSER_EDGE )
- Internet Explorer ( Browser::BROWSER_IE )
- Pocket Internet Explorer ( Browser::BROWSER_POCKET_IE )
- Galeon ( Browser::BROWSER_GALEON )
- Konqueror ( Browser::BROWSER_KONQUEROR )
- iCab ( Browser::BROWSER_ICAB )
- OmniWeb ( Browser::BROWSER_OMNIWEB )
- Phoenix ( Browser::BROWSER_PHOENIX )
- Firebird ( Browser::BROWSER_FIREBIRD )
- UCBrowser ( Browser::BROWSER_UCBROWSER )
- Firefox ( Browser::BROWSER_FIREFOX )
- Mozilla ( Browser::BROWSER_MOZILLA )
- Palemoon ( Browser::BROWSER_PALEMOON )
- curl ( Browser::BROWSER_CURL )
- wget ( Browser::BROWSER_WGET )
- Amaya ( Browser::BROWSER_AMAYA )
- Lynx ( Browser::BROWSER_LYNX )
- Safari ( Browser::BROWSER_SAFARI )
- Playstation ( Browser::BROWSER_PLAYSTATION )
- iPhone ( Browser::BROWSER_IPHONE )
- iPod ( Browser::BROWSER_IPOD )
- Google.s Android( Browser::BROWSER_ANDROID )
- Google.s Chrome( Browser::BROWSER_CHROME )
- GoogleBot( Browser::BROWSER_GOOGLEBOT )
- Yahoo!.s Slurp( Browser::BROWSER_SLURP )
- W3C.s Validator( Browser::BROWSER_W3CVALIDATOR )
- BlackBerry( Browser::BROWSER_BLACKBERRY )
Operating System Detection
This solution identifies the following Operating Systems:
- Windows ( Browser::PLATFORM_WINDOWS )
- Windows CE ( Browser::PLATFORM_WINDOWS_CE )
- Apple ( Browser::PLATFORM_APPLE )
- Linux ( Browser::PLATFORM_LINUX )
- Android ( Browser::PLATFORM_ANDROID )
- OS/2 ( Browser::PLATFORM_OS2 )
- BeOS ( Browser::PLATFORM_BEOS )
- iPhone ( Browser::PLATFORM_IPHONE )
- iPod ( Browser::PLATFORM_IPOD )
- BlackBerry ( Browser::PLATFORM_BLACKBERRY )
- FreeBSD ( Browser::PLATFORM_FREEBSD )
- OpenBSD ( Browser::PLATFORM_OPENBSD )
- NetBSD ( Browser::PLATFORM_NETBSD )
- SunOS ( Browser::PLATFORM_SUNOS )
- OpenSolaris ( Browser::PLATFORM_OPENSOLARIS )
- iPad ( Browser::PLATFORM_IPAD )
History and Legacy
Detecting the user’s browser type and version is helpful in web applications that harness some of the newer bleeding edge concepts. With the browser type and version you can notify users about challenges they may experience and suggest they upgrade before using such application. Not a great idea on a large scale public site; but on a private application this type of check can be helpful.
In an active project of mine we have a pretty graphically intensive and visually appealing user interface which leverages a lot of transparent PNG files. Because we all know how great IE6 supports PNG files it was necessary for us to tell our users the lack of power their browser has in a kind way.
Searching for a way to do this at the PHP layer and not at the client layer was more of a challenge than I would have guessed; the only script available was written by Gary White and Gary no longer maintains this script because of reliability. I do agree 100% with Gary about the readability; however, there are realistic reasons to desire the user.s browser and browser version and if your visitor is not echoing a false user agent we can take an educated guess.
I based this solution off of Gary White’s original work but have since replaced all of his original code. Either way, thank you to Gary. Sadly, I never was able to get in touch with him regarding this solution.
The testing with PHPUnit against known user agents available in tests/lists. Each file is tab delimited with the following fields:
User Agent, User Agent Type, Browser, Version, Operating System, Operating System Version
Источник