Using PHP to Detect iOS & Mobile  Users

This basic mobile_user_agent_switch() function will allow you to use PHP to detect iOS and mobile device visitors using one of the following:

Supported Devices

  • iPhone
  • iPad
  • Android
  • Blackberry

The mobile_user_agent_switch() Function

/*
*	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

Hopefully this helps someone else out there!

Looking for more detail?

This is only the tip of the iceberg. If you’re looking for a detailed mobile detection script I suggest checking out the mobile device detect script provided by detectmobilebrowsers.mobi.

It provides a more detailed check that will include:

  • Windows Mobile Devices
  • Palm Mobiles
  • Opera Mini Devices
  • Amazon Kindle
  • Much more…

At the time this script was overkill for my needs, so I wrote the basic function above to provide a lean solution to suite my needs: A basic PHP function to check for major mobile devices.

Resources

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.