- PHP get_browser() Function
- Definition and Usage
- Syntax
- Parameter Values
- Technical Details
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Как получить User Agent в PHP. Как настроить browscap.ini
- Как настроить PHP для работы с get_browser
- Связанные статьи:
- Something Useful
- strpos() must have returned non-false
- strpos() must have returned false
- strpos() must have returned non-false
PHP get_browser() Function
Look up the browscap.ini file and return the capabilities of the browser:
Definition and Usage
The get_browser() function looks up the user’s browscap.ini file and returns the capabilities of the user’s browser.
Syntax
Parameter Values
Parameter | Description |
---|---|
user_agent | Optional. Specifies the name of an HTTP user agent. Default is the value of $HTTP_USER_AGENT. You can bypass this parameter with NULL |
return_array | Optional. If this parameter is set to TRUE, the function will return an array instead of an object |
Technical Details
Return Value: | Returns an object or an array with information about the user’s browser on success, or FALSE on failure |
---|---|
PHP Version: | 4+ |
Changelog: | The return_array parameter was added in PHP 4.3.2 |
❮ PHP Misc Reference
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Как получить User Agent в PHP. Как настроить browscap.ini
User Agent — это строка, которая характеризует программу, делающую запрос к веб-серверу. Пример такой строки:
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
Как можно увидеть, по User Agent можно определить операционную систему и версию веб-браузера.
По своей сути User Agent является одним из заголовков протокола HTTP. Причём этот заголовок присылает сам клиент. Отсюда очень важное следствие — строка User Agent может быть подменена на абсолютно любое значение или отсутствовать вовсе. В веб-браузерах это можно сделать с помощью плагинов.
Поэтому всегда помните о том, что Пользовательский Агент может быть спуфлен (заменён). Причём если вы, например, сохраняете полученные значения в базу данных, то помните о необходимости фильтрации данных, поскольку без должной фильтрации пользовательских данных это может стать причиной уязвимости SQL-инъекция.
Итак, получить значение User Agent в PHP скрипте можно используя переменную $_SERVER[‘HTTP_USER_AGENT’]. Например:
Как настроить PHP для работы с get_browser
Ещё один способ — это использовать функцию get_browser. На самом деле, суть функции get_browser в том, чтобы показать возможности (поддерживаемые технологии) веб-браузера на основе User Agent. Причём необязательно для текущего пользователя — функция get_browser может в качество ввода принимать произвольную строку User Agent.
По умолчанию функция get_browser НЕ работает, поскольку требует дополнительной настройки в конфигурации PHP. Если не выполнить эту настройку, то при попытке использовать функцию get_browser вы будете получать примерно такое предупреждение:
Warning: get_browser(): browscap ini directive not set in /srv/http/tests.php on line 5
Точнее говоря, требуется скачать специальный файл с перечнем свойств веб-браузера и указать путь до него в php.ini (главном конфигурационном файле PHP).
Эти файлы размещены на сайте http://browscap.org/. Всего для PHP имеется 3 варианта:
- php_browscap.ini (17,095 KB). Стандартная версия файла, довольно полная.
- full_php_browscap.ini (85,513 KB). Самая большая версия файла со всеми возможными свойствами.
- lite_php_browscap.ini (463 KB). Облегчённый вариант, содержит основные браузеры и поисковые движки. Этот файл вполне подойдёт для большинства веб-сайтов.
Итак, скачайте один из этих файлов — тот, который больше подходит под ваши нужды.
Для примера я скачал файл full_php_browscap.ini. Переименуйте скаченный файл в browscap.ini.
Переместите этот файл в директорию /etc/php/
Теперь откройте файл /etc/php/php.ini. Найдите там раздел:
[browscap] ; http://php.net/browscap ;browscap = extra/browscap.ini
Удалите вторую строку, а третью раскомментируйте и в качестве значения укажите абсолютный путь до файла, чтобы получилось так:
[browscap] browscap = /etc/php/browscap.ini
ПРИМЕЧАНИЕ: В некоторых дистрибутивах путь до файла php.ini иной и зависит от версии PHP. К примеру, сейчас в Debian путь до файла следующий: /etc/php/8.1/apache2/php.ini
Чтобы изменения вступили в силу, перезапустите веб-сервер Apache.
На Debain, Ubuntu, Linux Mint, Kali Linux и их производных:
sudo systemctl restart apache2.service
На Arch Linux, BlackArch и их производных:
sudo systemctl restart httpd.service
Array ( [browser_name_regex] => ~^mozilla/5\.0 \(.*linux.*x86_64.*\).*applewebkit.*\(.*khtml.*like.*gecko.*\).*chrome/.* safari/.*$~ [browser_name_pattern] => Mozilla/5.0 (*Linux*x86_64*)*applewebkit*(*khtml*like*gecko*)*Chrome/* Safari/* [parent] => Chrome Generic [browser_bits] => 64 [platform] => Linux [platform_description] => Linux [platform_bits] => 64 [platform_maker] => Linux Foundation [device_name] => Linux Desktop [device_code_name] => Linux Desktop [comment] => Chrome Generic [browser] => Chrome [browser_type] => Browser [browser_maker] => Google Inc [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [javascript] => 1 [cssversion] => 3 [aolversion] => 0 [device_type] => Desktop [device_pointing_method] => mouse [renderingengine_name] => Blink [renderingengine_description] => a WebKit Fork by Google [renderingengine_maker] => Google Inc [browser_modus] => unknown [version] => 0.0 [majorver] => 0 [minorver] => 0 [platform_version] => unknown [alpha] => [beta] => [win16] => [win32] => [win64] => [backgroundsounds] => [vbscript] => [javaapplets] => [activexcontrols] => [ismobiledevice] => [istablet] => [issyndicationreader] => [crawler] => [isfake] => [isanonymized] => [ismodified] => [device_maker] => unknown [device_brand_name] => unknown [renderingengine_version] => unknown )
Обратите внимание, что в последних версиях PHP драмматически (в сотню раз) увеличена скорость работы функции get_browser.
При выборе нужного файла browscap.ini помните об их размерах, поскольку облегчённая версия от самой полной по размеру отличается примерно в 200 раз! При этом помните о расходе оперативной памяти на каждый процесс веб-сервера. Причём может быть повышенной потребление оперативной памяти даже если вы фактически не используете функцию get_browser.
Также помните о том, что вам нужно заботиться об обновлении файла browscap.ini.
Связанные статьи:
Something Useful
Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is $_SERVER[‘HTTP_USER_AGENT’] .
Note:
$_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. See the related manual page on superglobals for more information.
To display this variable, you can simply do:
Example #1 Printing a variable (Array element)
A sample output of this script may be:
There are many types of variables available in PHP. In the above example we printed an Array element. Arrays can be very useful.
$_SERVER is just one variable that PHP automatically makes available to you. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by looking at the output of the phpinfo() function used in the example in the previous section.
You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Internet Explorer you can do this:
Example #2 Example using control structures and functions
if ( strpos ( $_SERVER [ ‘HTTP_USER_AGENT’ ], ‘MSIE’ ) !== FALSE ) echo ‘You are using Internet Explorer.
‘ ;
>
?>?php
A sample output of this script may be:
You are using Internet Explorer.
Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up an introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual.
The second concept we introduced was the strpos() function call. strpos() is a function built into PHP which searches a string for another string. In this case we are looking for ‘MSIE’ (so-called needle) inside $_SERVER[‘HTTP_USER_AGENT’] (so-called haystack). If the needle is found inside the haystack, the function returns the position of the needle relative to the start of the haystack. Otherwise, it returns false . If it does not return false , the if expression evaluates to true and the code within its is executed. Otherwise, the code is not run. Feel free to create similar examples, with if, else, and other functions such as strtoupper() and strlen() . Each related manual page contains examples too. If you are unsure how to use functions, you will want to read both the manual page on how to read a function definition and the section about PHP functions.
We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:
Example #3 Mixing both HTML and PHP modes
if ( strpos ( $_SERVER [ ‘HTTP_USER_AGENT’ ], ‘MSIE’ ) !== FALSE ) ?>
strpos() must have returned non-false
You are using Internet Explorer
> else ?>
strpos() must have returned false
You are not using Internet Explorer
>
?>?php
A sample output of this script may be:
strpos() must have returned non-false
You are using Internet Explorer
Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on the result of strpos() . In other words, it depends on whether the string MSIE was found or not.