Search code examples
javascriptphphtmlmobilebrowser-detection

Mobile detection failing


I am trying to detect if my user is using a smartphone. I have tried so many different methods but nothing seems to detect if it is a smartphone.

The one below does not even echo $_SERVER['HTTP_USER_AGENT'];

     <?php
echo $_SERVER['HTTP_USER_AGENT'];
    $iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    $android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
    $palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
    $berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
    $ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

    if ($iphone || $android || $palmpre || $ipod || $berry == true) 
    { 
    header('Location: http://mobile.site.com/');
    }
    ?>

This is another script I tried that did not echo anything back.

<script type="text/javascript" >
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
<?php 
echo "I should redirect";
?>
}
</script>

I have also tried getting the screen size, but that does not show anything.

<script type="text/javascript">
  document.write(screen.width);
  if (screen.width <= 800) {
    window.location = "http://m.domain.com";
  }

</script>

I have also tried the very popular php script below, but it also echo's nothing for $detect.

    <?php 
require_once 'Mobile_Detect.php';
        $detect = new Mobile_Detect;
         echo $detect;
        if($detect->isMobile()) {
            header('Location: http://mobile.example1.com/');
            exit;
        }
?>

Solution

  • Please check that solution:

    if( strstr($_SERVER['HTTP_USER_AGENT'],'Android') ||
        strstr($_SERVER['HTTP_USER_AGENT'],'webOS') ||
        strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') ||
        strstr($_SERVER['HTTP_USER_AGENT'],'iPod')
    ){}