Mobile clients detection in PHP

 
<?
 
function detect_mobile()	{
 
	$mobile = TRUE;
	$useragent = $_SERVER['HTTP_USER_AGENT'];
 
	// don't forget to remove pipe from last one cause it will match everything in OR
	$pc_dstr =	'/('
			. 'X11|'
			. 'Windows NT|'
			. 'Macintosh'
			. ')/i';
 
	// don't forget to remove pipe from last one cause it will match everything in OR
	$mob_dstr =	 '/('
			. 'android|'
			. 'meego|'
			. 'iphone|'
			. 'ipad|'
			. 'ipod|'
			. 'cyanogen|'
			. 'mobile|'
			. 'mini|'
			. 'blackberry|'
			. 'cyanogen'
			. ')/i';
 
 
	if ( preg_match($pc_dstr, $useragent) > 0 )	{
		$mobile = FALSE;	
	}
 
	if ( preg_match($mob_dstr, $useragent) > 0 )	{
		$mobile = TRUE;	
	}
 
	return $mobile;
}
 
?>
 

This is the simple function you can include from file. By default there is an assumption that client is mobile. This can be changed by match for strings defined in $pc_dstr variable. There is also an another match for common strings used by mobile devices which can revert changes made by first match in case that identification contains some strings common for mobile devices too.

So a better description based on how it works should be "function to detect desktop/workstation client".

I'm using this on this site to decide if is it good to insert javascript function which enables fixed sidebar menu instead of static one.

author: niekto@niekde.sk (Jaroslav Petráš)

date: Wed, 19 Feb 2014 16:02:00 +0000

link: CyberAsylum.eu/mobile-clients-detection-in-php