首页 > 解决方案 > 基于 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。难道我做错了什么?是不是不够精准?

标签: phphtmlredirect

解决方案


您应该尝试使用此代码来检测用户的浏览器。

 $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();
}

参考


推荐阅读