User agent detect with PHP

Small PHP code snippet to make a quick detect if the browser that requests your page is on a mobile…

November 7, 2013


Small PHP code snippet to make a quick detect if the browser that requests your page is on a mobile device.

function isMobile(){
	$device = '';
	if( stristr($_SERVER['HTTP_USER_AGENT'],'ipad') ) {
		$device = "ipad";
	} else if( stristr($_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; 
}

If it’s a mobile device (that is to say an iphone, an ipad, an android or a blackberry) returns the $device variable. Else it returns false.

Author

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

Recommended

WP doesn’t send email? try this

Snippets for sending emails with Wordpress

February 8, 2020

Highlight text for search results in PHP

Useful code to highlight text occurences in search results or in a text. How to highlight text in a string…

September 2, 2016

How to add rel=”nofollow” to links with preg_replace()

Adding rel="nofollow" to external link is a good SEO practice.

September 22, 2015

Limit the number of categories for posts in WordPress

CHOOSE ONLY ONE CATEGORY WORDPRESS If you need to limit the number of categories used by the authors of your…

September 14, 2015

Reordering rows records on a mysql table with PHP

This PHP function lets you reorder records on a table when you have a field used for save the position.…

December 18, 2013

Scraping content with PHP as if it was jQuery

Building a spider or a bot needs some knowledge of regular expressions, you must know and use preg_match or preg_match_all…

December 8, 2013