php - 基于 HTTP_USER_AGENT 的 PHP 重定向
问题描述
我正在尝试基于用户代理重定向我的页面。我已经写了一段代码并在之前包含了它<!doctype html>
$SAFARI_URL = "https://example.com/ms/";
$OPERA_URL = "https://example.com/ms/";
$OTHER_URL = "https://example.com/";
$CHROME_URL = "https://example.com/";
// Redirection code
$HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];
function str_present($str,$substr)
{
$pos = strpos($str,$substr);
if($pos === false) {
return false;
}else {
return true;
}
}
if (str_present($HTTP_USER_AGENT, "Safari")){
Header ("Location: " . $SAFARI_URL);
}else if (str_present($HTTP_USER_AGENT, "Opera")){
Header ("Location: " . $OPERA_URL);
}else if (str_present($HTTP_USER_AGENT, "Chrome")){
Header ("Location: " . $CHROME_URL);
}else{
Header ("Location: " . $OTHER_URL);
}
问题是它不适用于 Chrome。难道我做错了什么?是不是不够精准?
解决方案
您应该尝试使用此代码来检测用户的浏览器。
$SAFARI_URL = "https://example.com/ms/";
$OPERA_URL = "https://example.com/ms/";
$OTHER_URL = "https://example.com/";
$CHROME_URL = "https://example.com/";
$user_agent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/'))
redirect($OPERA_URL );
elseif (strpos($user_agent, 'Edge'))
//redirect($url);
elseif (strpos($user_agent, 'Chrome'))
redirect($CHROME_URL );
elseif (strpos($user_agent, 'Safari'))
redirect($SAFARI_URL );
elseif (strpos($user_agent, 'Firefox'))
//redirect($url);
elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7'))
//redirect($url); //internet explorer
redirect($OTHER_URL);
}
function redirect($url) {
ob_start();
header('Location: '.$url);
ob_end_flush();
die();
}
推荐阅读
- javascript - 如何在 Angular 8 中从路由中隐藏 Header 组件的导航栏按钮?
- python - 我不明白为什么我的脚本没有遍历所有 string.split 元素?
- javascript - 使用 jest 为 event.preventDefault 编写一个单元案例
- angular - NavigateByUrl 在使用 angular-oauth2-oidc 的 onTokenReceived 中不起作用
- python - 获取模型 n_features 为 11 且输入 n_features 为 2 错误的原因是什么
- directx - 大于屏幕目标的 HLSL 渲染完全失败
- javascript - 当我在 p5 编辑器上运行此代码时,第 0 行出现错误
- r - 在名称的开头和结尾选择具有固定模式的列,以及可变的中间部分
- jquery - 如何在jquery中访问元素的第一个子元素
- r - 在 R 中的两个因素的 group_by() 中使用 lapply