我想让添加的用户代理留在页面上。如果没有检测到用户代理,则重定向。
这段代码的工作原理是
$useragent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($useragent, "useragent") === false) {
header("Location: http://google.com/");
}
所以我试着像这样添加多个用户代理,但是没有成功。
$useragent = $_SERVER['HTTP_USER_AGENT'];
if (
strpos($useragent, "agent1") === false ||
strpos($useragent, "agent2") === false ||
strpos($useragent, "agent2") === false
) {
header("Location: http://google.com/");
}
你可能需要一个比你的连续更新更简单的代码。strpos()
. 另外,你应该不分大小写地搜索。而且在每个页面访问时启动PCRE引擎可能不是最佳的。
所以我会保留 stripos()
这样的方法。
<?php
$partial_allowed_UA_names = ['mozilla', 'chrome', 'safari']; # <----- Config here.
$go_away = true;
foreach ($partial_allowed_UA_names as $v) {
if (stripos($_SERVER['HTTP_USER_AGENT'], $v) !== false) {
$go_away = false;
break;
}
}
if ($go_away) header('Location: https://www.google.com/');
?>
问候
您可以使用 preg_match()
而不是。
$useragent = $_SERVER['HTTP_USER_AGENT'];
$agents = ['agent1', 'agent2', 'agent3']; //array of predefined names of agents
if (!preg_match('/' . implode('|', $agents) . '/i', $useragent)) { //check if current user agent is not enlisted
header("Location: http://google.com/");
}