- Saved searches
- Use saved searches to filter your results more quickly
- olegkoval/php-user_info
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- Saved searches
- Use saved searches to filter your results more quickly
- marufhasan1/user_info
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Вывод информации о пользователе на PHP
- Как работает PHP класс «Информация о пользователе» по user-agent?
- Описание работы методов класса:
- Метод $this->load( $file_and_array_name ) загрузчик
- Метод $this->set_ip()
- Метод $this->set_browser() файл массива: arrays / browsers.php
- Метод $this->set_operating_system() файл массива: arrays / operating_systems.php
- Метод $this->set_robot() файл массива: arrays / robots.php
- Метод $this->set_mobile() файл массива: arrays / mobiles.php
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
PHP class to get information about the site visitor (IP, reverse DNS, referer, OS, etc. )
olegkoval/php-user_info
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
PHP class to get information about the website visitor (IP, reverse DNS, referer, OS, etc. )
Use Composer to install the library:
composer require olegkoval/php-user-info
- Call methods to get info about the website visitor:
- $UserInfo->getIP() — get IP of visitor
- $UserInfo->getReverseDNS() — get Reverse DNS of visitor
- $UserInfo->getCurrentURL() — get current URL
- $UserInfo->getRefererURL() — get Referer URL
- $UserInfo->getDevice() — get Device type (PC/iPad/iPhone/etc. ) of visitor
- $UserInfo->getOS() — get OS of visitor
- $UserInfo->getBrowser() — get Browser type of visitor
- $UserInfo->getLanguage() — get Browser Language of visitor
- $UserInfo->getCountryCode() — get Country Code of visitor
- $UserInfo->getCountryName() — get Country Name of visitor
- $UserInfo->getRegionCode() — get Region Code of visitor
- $UserInfo->getRegionName() — get Region Name of visitor
- $UserInfo->getCity() — get City of visitor
- $UserInfo->getZipcode() — get Zipcode of visitor
- $UserInfo->getLatitude() — get Latitude of visitor
- $UserInfo->getLongitude() — get Longitude of visitor
- $UserInfo->isProxy() — check if connection was through proxy
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Getting The Client Information (Client’s IP Address,Operating System,Browser Name,Device Type) in PHP
marufhasan1/user_info
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Getting The Client Information (Client’s IP Address,Operating System,Browser Name,Device Type) in PHP
include('UserInfo.php'); //Or Use Require function require('UserInfo.php');
If you want to get the client IP Address, Use this Method, This Method will return Client IP Address
require('user_info.php'); echo UserInfo::get_ip()
If you want to get the client Operating System Name, Use this Method, This Method will return Client Operating System
require('user_info.php'); echo UserInfo::get_os();
If you want to get the client’s Browser Name, Use this Method, This Method will return Client’s Browser Name
require('user_info.php'); echo UserInfo::get_browser();
If you want to get the client’s Device Type Then Use this Method, This Method will return Client’s Device Type Name Such as Mobile,Tablet,Computer
require('user_info.php'); echo UserInfo::get_device();
About
Getting The Client Information (Client’s IP Address,Operating System,Browser Name,Device Type) in PHP
Вывод информации о пользователе на PHP
При работе с сайтами может понадобиться такая информация о пользователе, как IP, браузер, ОС и некоторая другая информация. В выводе этой информации нам поможет PHP
— информация всегда будет полезна для учета статистики. Решение есть в виде готового скрипта на PHP, выводящего всю доступную информацию о зашедшем пользователе:
- IP посетителя
- Вход с ПК-браузера или с браузера мобильного устройства
- Название браузера
- Версия браузера
- Название ОС
- Версия/ядро ОС
- Название браузера мобильного устройства
- Вход осуществил человек или робот
- Какой поисковой системы принадлежит робот
Как работает PHP класс «Информация о пользователе» по user-agent?
Из папки arrays загружаются ассоциативные массивы, содержащие аббревиатуры или короткие название браузеров, операционных систем или роботов, которые встречаются в строке user-agent, полученную из браузера. После получения данных динамично вызываются все методы, имеющие префикс set_ и заполняют переменные класса, так как только они являются публичными, и только их можно вывести за пределы видимости класса.
load( $file ); > // Данные пользователя $this->agent = (@$_SERVER['HTTP_USER_AGENT'])? $_SERVER['HTTP_USER_AGENT'] : ''; // Вызываем методы для заполнения данных пользователя $setMethods = array('set_ip', 'set_browser', 'set_operating_system', 'set_robot', 'set_mobile'); foreach($setMethods as $method) < $this->$method(); > > private function load( $file_and_array_name ) < /* * Загружает массивы из папки с массивами */ $Load = require_once( dirname( __FILE__ ) ) . '/arrays/'.$file_and_array_name.'.php'; $this->$file_and_array_name = (!count($Load))? array() : $Load; > private function set_ip() < $this->ip = $_SERVER['REMOTE_ADDR']; return True; > private function set_browser() < if (is_array($this->browsers) and count($this->browsers) > 0) < foreach ($this->browsers as $key => $val) < if (preg_match("|".preg_quote($key).".*?([0-9\.]+)|i", $this->agent, $match)) < $this->is_browser = TRUE; $this->version = $match[1]; $this->browser = $val; $this->browser_full_name = $match[0]; return True; > > > return False; > private function set_operating_system() < if (is_array($this->operating_systems) AND count($this->operating_systems) > 0) < foreach ($this->operating_systems as $key => $val) < if (preg_match("|".preg_quote($key).".*?([a-zA-Z]?[0-9\.]+)|i", $this->agent, $match)) < $this->operating_system = $val; $this->os_version = $match[1]; return True; > > > $this->operating_system = 'Unknown'; > private function set_robot() < if (is_array($this->robots) AND count($this->robots) > 0) < foreach ($this->robots as $key => $val) < if (preg_match("|".preg_quote($key)."|i", $this->agent)) < $this->is_robot = TRUE; $this->robot = $val; return TRUE; > > > return FALSE; > private function set_mobile() < if (is_array($this->mobiles) AND count($this->mobiles) > 0) < foreach ($this->mobiles as $key => $val) < if (FALSE !== (strpos(strtolower($this->agent), $key))) < $this->is_mobile = TRUE; $this->mobile = $val; return TRUE; > > > return FALSE; > > ?>
Это был пример того, как выглядит массив с «браузерами». Переменную, содержащую сам массив, указывать не нужно, ибо достаточно просто начать код с return. Если данный файл вызвать через require или require_once, а результат выполнения присвоить переменной, данная переменная будет содержать в себе массив (как это делает метод $this->load() в нашем классе).
'Flock', 'SeaMoney' => 'SeaMonkey', 'Chrome' => 'Chrome', 'Opera' => 'Opera', 'MSIE' => 'Internet Explorer', 'Internet Explorer' => 'Internet Explorer', 'Shiira' => 'Shiira', 'Firefox' => 'Firefox', 'Chimera' => 'Chimera', 'Phoenix' => 'Phoenix', 'Firebird' => 'Firebird', 'Camino' => 'Camino', 'Netscape' => 'Netscape', 'OmniWeb' => 'OmniWeb', 'Safari' => 'Safari', 'Mozilla' => 'Mozilla', 'Konqueror' => 'Konqueror', 'icab' => 'iCab', 'Lynx' => 'Lynx', 'Links' => 'Links', 'hotjava' => 'HotJava', 'amaya' => 'Amaya', 'IBrowse' => 'IBrowse' ); ?>
Описание работы методов класса:
Главный метод — конструктор «__construct» в момент вызова класса AboutGuest выполняется первым, тем самым играет ключевую роль в работе класса. Первым делом создает массивы данных для работы остальных методов. Объект $this->agent содержит в себе ничто иное, как $_SERVER[‘HTTP_USER_AGENT’], из которого мы вытаскиваем нужную нам информацию браузера.
Метод $this->load( $file_and_array_name ) загрузчик
Данный метод загружает из папки arrays массивы и присваивает их переменной, указанной в значении атрибута $file_and_array_name. Данный атрибут так же является названием файла из папки arrays.
Метод $this->set_ip()
Он возвращает значение из массива $_SERVER с ключом REMOTE_ADDR, как известно, $_SERVER[‘REMOTE_ADDR’] это IP пользователя, доступный браузеру.
Метод $this->set_browser() файл массива: arrays / browsers.php
После того, как метод $this->load загрузил массивы, этот метод будет работать с массивом из объекта $this->browsers. Как только он находит совпадение ключа массива с содержимым строки из $this->agent, он присваивает объекту $this->browser значение ключа из массива $this->browsers. Так же данный метод присваивает и версию браузера в $this->version. Так как браузер уже нашел совпадение, это не вызывает сомнения, что пользователь зашел с браузера, а не выполнил вход на сайт через скрипт. Присваиваем $this->is_browser значение True;
Метод $this->set_operating_system() файл массива: arrays / operating_systems.php
Работает аналогично методу $this->set_browser за исключением того, что, как массив проверки совпадении, он пользуется объектом $this->operating_systems, который получил массив из файла arrays/operating_systems.php после выполнения метода $this->load(). К сожалению, браузеры не столь активно делятся версией операционной системы. Иногда можно получить непонятные цифры вместо версии. Так что будете осторожны, когда пользуетесь $this->os_version. Название операционной системы содержится в $this->operating_system (не путать с $this->os_version)
Метод $this->set_robot() файл массива: arrays / robots.php
Проверяем, является ли посетитель роботом или нет. Если он является роботом, тогда значение для $this->is_robot будет TRUE; в значение $this->robot будет содержать название поисковика, запустившего робота на сайт (Google Bot, Yandex Bot, Rambler Bot…)
Метод $this->set_mobile() файл массива: arrays / mobiles.php
Работает аналогично методу $this->set_operating_system(), только присваивает объекту $this->mobile название марки телефона/ Значение $this->is_mobile будет TRUE в случае захода с мобильного телефона, смартфона или планшета.
agent
IP: $AboutGuest->ip Браузер: $AboutGuest->browser версия: $AboutGuest->version
Операционная система: $AboutGuest->operating_system версия: $AboutGuest->os_version
Являюсь роботом? ". $AboutGuest->is_robot ."
Робот принадлежит: $AboutGuest->robot
Зашел с мобильного? ". $AboutGuest->is_mobile ."
Телефон: $AboutGuest->mobile
"; ?>
Результат работы скрипта в разных браузерах может разным. Причина в том, что браузеры не выдают по PHP информацию из $_SERVER[‘HTTP_USER_AGENT’] одинаково, в добавок, через CRON или file_get_contents можно отправить PHP любое искусственное значение для $_SERVER[‘HTTP_USER_AGENT’], а с этим уже ничего не поделать.