How can I detect Android phones and Android tablets differently using the user agent header?

蓝咒 提交于 2020-01-02 03:48:06

问题


For my site I need to be able to tell the difference between when an Android tablet visits and when an Android phone visits. It needs to be detected before the page is sent to the user so using JavaScript to check the screen res isn't an option.

At the moment I use this to detect an android device: stripos($ua, 'android')

Is there anything unique thar a tablet has in it's user agent?


回答1:


You can use PHP's $_SERVER['HTTP_USER_AGENT'] then case-insensitive eregi functions to look for the following, which assumes the browser developer followed Android's guidelines on user agent specification:

$ua = $_SERVER['HTTP_USER_AGENT'];
if (eregi('Android', $ua) && eregi('Mobile', $ua)) $platform = "Android Phone";
elseif (eregi('Android', $ua) && !eregi('Mobile', $ua)) $platform = "Android Tablet";

It's not foolproof but it's a start.




回答2:


Checkout the WURFL project. It should be able to help you out not only in Android Phone and Android Tablet scenario but also other devices as well.




回答3:


@Patrick Kershner, your code only works for the family of Apple products. Each Apple device sends its own UA, but that's not the case with Android devices. In fact, the author of this post needs to know whether the Android device is a tablet or a phone without using Javascript. The code submitted by user user336828 is a great workaround for this, although not 100% reliable: some clone/white-label/low quality devices may send exactly the same UA string from both tablets and phones, but I think this should work with most known brand's devices. I just tested that code on both an Android phone and a tablet and it's working.




回答4:


if(strstr($_SERVER['HTTP_USER_AGENT'],'iPod') ||   strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPad') || strstr($_SERVER['HTTP_USER_AGENT'],'Android')){ 
    //do something...
}

Worked for me



来源:https://stackoverflow.com/questions/3952452/how-can-i-detect-android-phones-and-android-tablets-differently-using-the-user-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!