代码之家  ›  专栏  ›  技术社区  ›  Mario83

基于HTTP_用户_代理的PHP重定向

  •  1
  • Mario83  · 技术社区  · 7 年前

    <!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 回复  |  直到 7 年前
        1
  •  0
  •   Gufran Hasan    7 年前

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

     $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

    推荐文章