Categories
Development

Simple Mobile Detection Redirect

Been working on a simple mobile version of a website I’d done for a client in the past recently. We can a user on most popular mobile devices to be automatically redirected to the mobile version of the site when they visit the main website.

So I went way back to some User-Agent sniffing to accomplish this. I thought I was done with the whole User-Agent redirecting different versions of site’s, but in this case it does work really well.

Just collect the User-Agent header using PHP there run it against a switch statement for each mobile device we’re checking against.

Just look for an instance of a device specific string using preg_match() in PHP.

iPod/iPhone and Android example:

case (preg_match('/ipod/i', $user_agent) || preg_match('/iphone/i', $user_agent));
        header('Location: ' . $redirect);
	exit;
break;
 
case (preg_match('/android/i', $user_agent));
        header('Location: ' . $redirect);
	exit;
break;