基于HTTP_USER_AGENT

时间:2018-12-03 10:55:20

标签: php html5 redirect

我正在尝试根据用户代理重定向页面。我已经编写了一段代码,并将其包含在<!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。难道我做错了什么?不够精确吗?

1 个答案:

答案 0 :(得分:0)

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

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

Reference