PHP Device Detection

PHP Device Detection

For anyone who wants to use it… This is a way to detect devices with PHP particularly if a visitor to your web site is using a mobile device browser.

$_SERVER['HTTP_USER_AGENT'] detect device
Code:

/*
*   Mobile device detection
*/

if( !function_exists('mobile_user_agent_switch') ){
    function mobile_user_agent_switch(){
        $device = '';
 
        if( stristr($_SERVER['HTTP_USER_AGENT'],'ipad') ) {
            $device = "ipad";
        } else if( stristr($_SERVER['HTTP_USER_AGENT'],'iphone') || strstr($_SERVER['HTTP_USER_AGENT'],'iphone') ) {
            $device = "iphone";
        } else if( stristr($_SERVER['HTTP_USER_AGENT'],'blackberry') ) {
            $device = "blackberry";
        } else if( stristr($_SERVER['HTTP_USER_AGENT'],'android') ) {
            $device = "android";
        }
 
        if( $device ) {
            return $device;
        } return false; {
            return false;
        }
    }
}
The function will return one of the following values for you to work with in your code:

> ipad
> iphone
> blackberry
> android
> unknown

OR you can do something like this:

<?php


/* detect mobile device*/
$ismobile = 0;
$container = $_SERVER['HTTP_USER_AGENT'];

// A list of mobile devices
$useragents = array (

'Blazer' ,
'Palm' ,
'Handspring' ,
'Nokia' ,
'Kyocera',
'Samsung' ,
'Motorola' ,
'Smartphone',
'Windows CE' ,
'Blackberry' ,
'WAP' ,
'SonyEricsson',
'PlayStation Portable',
'LG',
'MMP',
'OPWV',
'Symbian',
'EPOC',

);

foreach ( $useragents as $useragents ) {
if(strstr($container,$useragents)) {
$ismobile = 1;
}
}



if ( $ismobile == 1 ) {
echo "<p>mobile device</p>";
echo $_SERVER['HTTP_USER_AGENT'];
}

?>

Isn’t this amazing?!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>