How to determine if the device is Mobile or Desktop?

为君一笑 提交于 2019-12-08 01:24:30

问题


I have read a lot of articles and looked for solutions to detect mobile devices. Actually a came across https://github.com/serbanghita/mobile-detect but it's a quite massive php class.

I actually want a very simple solution. I want to determine if the user's browser is Mobile/iPad/etc OR Desktop. So I want something like this:

<?php

require('detector.php');

if(isMobile() === true)
{
   header('mobile.php');
   exit();
}
else
{
   header('desktop.php');
   exit();
}

?>

A very simple solution is needed which I can place to any page without installing composer or any php framework.

How is this actually possible?


回答1:


Have you actually tried to use the project you discovered. I'd say that server side mobile detection IS a huge task with plenty of detail checks to ensure the correct outcome.

And using this class is completely easy. From the example directory:

require_once '../Mobile_Detect.php';
$detect = new Mobile_Detect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');

Now you have a variable with one of three values: "tablet", "phone" or "computer", and you can react to this.

Please note that even if you are able to use this library without Composer, it will be updated regularly (as in "once every month"), because new devices get on the market and need to be detected. You will have to update this library at some point. Using Composer makes this very easy.




回答2:


If you really don't want to include that class into your code, Mozilla indicates that it is "good enough" to search for the string "mobi" in the user agent.

<?php
if (stristr($_SERVER['HTTP_USER_AGENT'],'mobi')!==FALSE) {
    echo 'mobile device detected';
}
?>



回答3:


You can redirect the link with
and in controller you can check with

$keybord = app::get('keyboard')
if($keyboard == mobile ){
    redirect ('mobile');
}else{
   redirect ('desktop');
}   



回答4:


I've found this simple line to be pretty reliable and easy to implement.. without having the need to add one extra class.

if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) {
   echo "running on mobile";
}


来源:https://stackoverflow.com/questions/31437868/how-to-determine-if-the-device-is-mobile-or-desktop

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