Super dumb easily used mobile user agent detection function in PHP

Here’s a totally awesome mind-blowing function to detect whether the given device is a mobile device. The user agent is more reliable than using the media attribute in your stylesheet links. THERE IS A CAVEAT! This caveat is that this function checks currently only three devices – Android devices, iPhones, and BlackBerry devices (BlackBerrys? BlackBerries? Given it’s a corporate trademarked sort of thing, I’m thinking it’s the former). But you can probably see how you might expand the list. It stuffs the result of the check into the session (by default) so as to not repeatedly run through the array.

<?php
 
function isMobile($session = TRUE) {
 
        if ($session && session_id() === "") {
            session_start();
        }
 
        if ($session && isset($_SESSION["isMobile"])) {
            return (bool)$_SESSION["isMobile"];
        }
 
        if (empty($_SERVER["HTTP_USER_AGENT"])) {
            // sorry, unknowns!
            return FALSE;
        }
 
        $agent = $_SERVER["HTTP_USER_AGENT"];
        $mobile = array(
            "Android",
            "iPhone",
            "AvantGo",
            "BlackBerry"
        );
 
        foreach ($mobile as $m) {
            if (stripos($agent, $m)) {
                if ($session) {
                    $_SESSION["isMobile"] = TRUE;
                }
 
                return TRUE;
            }
        }
 
        if ($session) {
            $_SESSION["isMobile"] = FALSE;
        }
 
        return FALSE;
}
?>

Now, you simply call it like so:

<?php
	if (isMobile()) {
		$sheet = "mobile.css";
	} else {
		$sheet = "styles.css";
	}
?>

Leave a comment

RSS feed for comments on this post