[英]Combining multiple strpos() in an if () statement
I'm trying to make added user agent stay on a page.我正在尝试使添加的用户代理留在页面上。 If user agent is not detected, then redirect.如果未检测到用户代理,则重定向。
This code works此代码有效
$useragent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($useragent, "useragent") === false) {
header("Location: http://google.com/");
}
So I tried to add multiple user agent like this but didn't work.所以我尝试像这样添加多个用户代理,但没有奏效。
$useragent = $_SERVER['HTTP_USER_AGENT'];
if (
strpos($useragent, "agent1") === false ||
strpos($useragent, "agent2") === false ||
strpos($useragent, "agent2") === false
) {
header("Location: http://google.com/");
}
You can use preg_match()
instead.您可以改用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/");
}
You may want a code that is simpler to update than your successive strpos()
.您可能需要一个比后续strpos()
更易于更新的代码。 Also, you should search case-insensitively.此外,您应该不区分大小写搜索。 And firing the PCRE engine at each page access may not be optimal.并且在每个页面访问时触发 PCRE 引擎可能不是最佳的。
So I would keep the stripos()
approach like this:所以我会保持这样的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/');
?>
Best regards此致
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.