用 PHP 写成的通用设备识别库,输入 User Agent 或浏览器的 Client Hints,返回设备、客户端、操作系统、品牌与型号几类结果。设备这一层覆盖 desktop、tablet、mobile、tv、cars、console 等形态,客户端一侧区分浏览器、feed reader、media player、PIM,机器人流量与移动端的识别也在覆盖范围内。代码除 DeviceDetector 主类与 ClientHints 之外,还在 DeviceDetector\Parser\Device 命名空间下按维度拆出解析器,文档示例演示了从自动加载到解析设备的具体写法。安装走 Composer,引入 matomo/device-detector 后照示例接上自动加载即可用。浏览器逐步缩减 UA、转向 Client Hints 的当下,两条输入路径并存意味着老日志与新流量都不至于漏判。适合在服务端做访问统计、日志分析或按终端分流页面的 PHP 项目,尤其是已经围绕 Matomo 搭数据链路的团队。以 LGPL-3.0 许可发布。
The Universal Device Detection library that parses User Agents and Browser Client Hints to detect devices (desktop, tablet, mobile, tv, cars, console, etc.), clients (browsers, feed readers, media players, PIMs, ...), operating systems, brands and models.
Using DeviceDetector with composer is quite easy. Just add matomo/device-detector to your projects requirements.
composer require matomo/device-detector
And use some code like this one:
require_once 'vendor/autoload.php';
use DeviceDetector\ClientHints;
use DeviceDetector\DeviceDetector;
use DeviceDetector\Parser\Device\AbstractDeviceParser;
// OPTIONAL: Set version truncation to none, so full versions will be returned
// By default only minor versions will be returned (e.g. X.Y)
// for other options see VERSION_TRUNCATION_* constants in DeviceParserAbstract class
AbstractDeviceParser::setVersionTruncation(AbstractDeviceParser::VERSION_TRUNCATION_NONE);
$userAgent = $_SERVER['HTTP_USER_AGENT']; // change this to the useragent you want to parse
// Client Hints are optional
// If you want to use them your server must announce that it supports client hints, using the Accept-CH header to specify the hints that it is interested in receiving.
// See e.g. https://developer.mozilla.org/en-US/docs/Web/HTTP/Client_hints
$clientHints = ClientHints::factory($_SERVER);
$dd = new DeviceDetector($userAgent, $clientHints);
// OPTIONAL: Set caching method
// By default static cache is used, which works best within one php process (memory array caching)
// To cache across requests use caching in files or memcache. Several cache bridges are supported:
// $dd->setCache(new DeviceDetector\Cache\DoctrineBridge(...));
// $dd->setCache(new DeviceDetector\Cache\LaravelCache(...));
// $dd->setCache(new DeviceDetector\Cache\PSR6Bridge(...));
// $dd->setCache(new DeviceDetector\Cache\PSR16Bridge(...));
// Instead of `...` provide respective cache object, for example:
// $dd->setCache(new DeviceDetector\Cache\PSR6Bridge(new Symfony\Component\Cache\Adapter\ApcuAdapter('matomo')));
// OPTIONAL: Set custom yaml parser
// By default Spyc will be used for parsing yaml files. You can also use another yaml parser.
// You may need to implement the Yaml Parser facade if you want to use another parser than Spyc or [Symfony](https://github.com/symfony/yaml)
// $dd->setYamlParser(new DeviceDetector\Yaml\Symfony());
// $dd->setYamlParser(new DeviceDetector\Yaml\Pecl());
// OPTIONAL: If called, getBot() will only return true if a bot was detected (speeds up detection a bit)
// $dd->discardBotInformation();
// OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then)
// $dd->skipBotDetection();
$dd->parse();
if ($dd->isBot()) {
// handle bots,spiders,crawlers,...
$botInfo = $dd->getBot();
} else {
$clientInfo = $dd->getClient(); // holds information about browser, feed reader, media player, ...
$osInfo = $dd->getOs();
$device = $dd->getDeviceName();
$brand = $dd->getBrandName();
$model = $dd->getModel();
}
Methods check device type:
$dd->isSmartphone();
$dd->isFeaturePhone();
$dd->isTablet();
$dd->isPhablet();
$dd->isConsole();
$dd->isPortableMediaPlayer();
$dd->isCarBrowser();
$dd->isTV();
$dd->isSmartDisplay();
$dd->isSmartSpeaker();
$dd->isCamera();
$dd->isWearable();
$dd->isPeripheral();
Methods check client type:
$dd->isBrowser();
$dd->isFeedReader();
$dd->isMobileApp();
$dd->isPIM();
$dd->isLibrary();
$dd->isMediaPlayer();
Get OS family:
use DeviceDetector\Parser\OperatingSystem;
$osFamily = OperatingSystem::getOsFamily($dd->getOs('name'));
Get browser family:
use DeviceDetector\Parser\Client\Browser;
$browserFamily = Browser::getBrowserFamily($dd->getClient('name'));
Instead of using the full power of DeviceDetector it might in some cases be better to use only specific parsers. If you aim to check if a given useragent is a bot and don't require any of the other information, you can directly use the bot parser.
require_once 'vendor/autoload.php';
use DeviceDetector\Parser\Bot AS BotParser;
$botParser = new BotParser();
$botParser->setUserAgent($userAgent);
// OPTIONAL: discard bot information. parse() will then return true instead of information
$botParser->discardDetails();
$result = $botParser->parse();
if (!is_null($result)) {
// do not do anything if a bot is detected
return;
}
// handle non-bot requests
Alternatively to using composer you can also use the included autoload.php.
This script will register an autoloader to dynamically load all classes in DeviceDetector namespace.
Device Detector requires a YAML parser. By default Spyc parser is used.
As this library is not included you need to include it manually or use another YAML parser.
<?php
include_once 'path/to/spyc/Spyc.php';
include_once 'path/to/device-detector/autoload.php';
use DeviceDetector\ClientHints;
use DeviceDetector\DeviceDetector;
use DeviceDetector\Parser\Device\AbstractDeviceParser;
// OPTIONAL: Set version truncation to none, so full versions will be returned
// By default only minor versions will be returned (e.g. X.Y)
// for other options see VERSION_TRUNCATION_* constants in DeviceParserAbstract class
AbstractDeviceParser::setVersionTruncation(AbstractDeviceParser::VERSION_TRUNCATION_NONE);
$userAgent = $_SERVER['HTTP_USER_AGENT']; // change this to the useragent you want to parse
$clientHints = ClientHints::factory($_SERVER); // client hints are optional
$dd = new DeviceDetector($userAgent, $clientHints);
// ...
By default, DeviceDetector uses a built-in array cache. To get better performance, you can use your own caching solution:
DeviceDetector\Cache\CacheInterface// Example with PSR-6 and Symfony
$cache = new \Symfony\Component\Cache\Adapter\ApcuAdapter();
$dd->setCache(
new \DeviceDetector\Cache\PSR6Bridge($cache)
);
// Example with PSR-16 and ScrapBook
$cache = new \MatthiasMullie\Scrapbook\Psr16\SimpleCache(
new \MatthiasMullie\Scrapbook\Adapters\Apc()
);
$dd->setCache(
new \DeviceDetector\Cache\PSR16Bridge($cache)
);
// Example with Doctrine
$cache = new \Doctrine\Common\Cache\ApcuCache();
$dd->setCache(
new \DeviceDetector\Cache\DoctrineBridge($cache)
);
// Example with Laravel
$dd->setCache(
new \DeviceDetector\Cache\LaravelCache()
);
This is a free/libre library under license LGPL v3 or later.
Your pull requests and/or feedback is very welcome!
Sometimes it may be useful to generate the list of most used user agents on your website, extracting this list from your access logs using the following command:
zcat ~/path/to/access/logs* | awk -F'"' '{print $6}' | sort | uniq -c | sort -rn | head -n20000 > /home/matomo/top-user-agents.txt
Created by the Matomo team, Stefan Giehl, Matthieu Aubry, Michał Gaździk, Tomasz Majczak, Grzegorz Kaszuba, Piotr Banaszczyk and contributors.
Together we can build the best Device Detection library.
We are looking forward to your contributions and pull requests!
See also: QA at Matomo
cd /path/to/device-detector
curl -sS https://getcomposer.org/installer | php
php composer.phar install
./vendor/bin/phpunit
There are already a few ports of this tool to other languages:
| 日期 | 榜单 | 排名 | 周期新增 | 总 STAR |
|---|