functions.php
编辑主题目录下的functions.php
文件,在<?php
后增加
include 'agent.php';
agent.php
创建agent.php
文件内容:
<?php
function getOS($agent) {
$osPatterns = [
'Windows' => [
['pattern' => '/windows/i', 'versions' => [
['version' => 'XP', 'match' => '/nt 5.1/i'],
['version' => 'Vista', 'match' => '/nt 6.0/i'],
['version' => '7', 'match' => '/nt 6.1/i'],
['version' => '8', 'match' => '/nt 6.2/i'],
['version' => '8.1', 'match' => '/nt 6.3/i'],
['version' => '10/11', 'match' => '/nt 10.0/i'],
['version' => '', 'match' => '/windows/i'],
]],
],
'Android' => [
['pattern' => '/android/i', 'versions' => [
['version' => 'Nougat', 'match' => '/android 7/i'],
['version' => 'Oreo', 'match' => '/android 8/i'],
['version' => 'Pie', 'match' => '/android 9/i'],
['version' => 'Q', 'match' => '/android 10/i'],
['version' => '11', 'match' => '/android 11/i'],
['version' => '12', 'match' => '/android 12/i'],
['version' => '13', 'match' => '/android 13/i'],
['version' => '14', 'match' => '/android 14/i'],
['version' => '15', 'match' => '/android 15/i'],
['version' => '', 'match' => '/android/i'],
]],
],
'Ubuntu' => [
['pattern' => '/ubuntu/i', 'versions' => [['version' => '', 'match' => '/ubuntu/i']]],
],
'Linux' => [
['pattern' => '/linux/i', 'versions' => [['version' => '', 'match' => '/linux/i']]],
],
'iPhone' => [
['pattern' => '/iPhone/i', 'versions' => [['version' => '', 'match' => '/iPhone/i']]],
],
'MacOS' => [
['pattern' => '/mac/i', 'versions' => [['version' => '', 'match' => '/mac/i']]],
],
'Unknown' => [
['pattern' => '/.*/', 'versions' => [['version' => '', 'match' => '/.*/']]],
],
];
foreach ($osPatterns as $osName => $patterns) {
foreach ($patterns as $patternData) {
if (preg_match($patternData['pattern'], $agent)) {
foreach ($patternData['versions'] as $versionData) {
if (preg_match($versionData['match'], $agent)) {
$os = $osName . ($versionData['version'] ? " {$versionData['version']} · " : " · ");
echo $os;
return;
}
}
}
}
}
}
function getBrowser($agent) {
$browserPatterns = [
'Internet Explorer' => [
['pattern' => '/MSIE\s([^\s|;]+)/i'],
],
'FireFox' => [
['pattern' => '/FireFox\/([^\s]+)/i'],
],
'MicroSoft Edge' => [
['pattern' => '/Edge([\d]*)\/([^\s]+)/i'],
],
'QQ Browser' => [
['pattern' => '/QQ/i'],
],
'Wechat' => [
['pattern' => '/MicroMessenger/i'],
],
'Opera' => [
['pattern' => '/Opera[\s|\/]([^\s]+)/i'],
],
'Google Chrome' => [
['pattern' => '/Chrome([\d]*)\/([^\s]+)/i'],
],
'Safari' => [
['pattern' => '/safari\/([^\s]+)/i'],
],
'Unknown' => [
['pattern' => '/.*/'],
],
];
foreach ($browserPatterns as $browserName => $patterns) {
foreach ($patterns as $patternData) {
if (preg_match($patternData['pattern'], $agent)) {
echo $browserName;
return;
}
}
}
}
?>
comment.php
在/public/comment.php适当的地方(如第123行<time>
标签内)插入以下代码以引用用户操作系统及浏览器信息。
<?php getOS($comments->agent); ?><?php getBrowser($comments->agent); ?>