I needed a quick way to include different files based on the if the visitor to a site is on a mobile device or a regular browser/computer.
Every browser has a user agent depending on the operating system, browser and system.
below are some common use agents, they can be found by echoing the server variable HTTP_USER_AGENT
< ?php echo $_SERVER['HTTP_USER_AGENT']; ?>
FireFox
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7
Safari Mac
Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-en) AppleWebKit/523.10.3 (KHTML, like Gecko) Version/3.0.4 Safari/523.10
Safari Windows
Mozilla/5.0 (Windows; U; Windows NT 6.0; en) AppleWebKit/522.13.1 (KHTML, like Gecko) Version/3.0.2 Safari/522.13.1
Nexus One
Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD56C) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17
Apple iPhone
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3
Apple iPod Touch
Mozilla/5.0 (iPod; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3A100a Safari/419.3
Internet Explorer
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)
PHP mobileAgent() Function
Here is my function, is it simple PHP function, is expects one paramerter, and array or expected user agents, but by leaving it blank, the function will use the default user agents.
Update: I have added more mobile user agents for older Android models, Blackberrry’s and the iPhone simulator. .
< ?php
function mobileAgent($custom_agents = array()) {
$agents = array_merge($custom_agents, array(
'iphone', // Apple iPhone
'ipod', // Apple iPod touch
'aspen', // iPhone simulator
'nexus', // Nexus One Android
'dream', // Pre 1.5 Android
'android', // 1.5+ Android
'cupcake', // 1.5+ Android
'blackberry9500', // Storm
'blackberry9530', // Storm
'opera mini', // Opera mobile
'webos', // Nokia Browser
'incognito', // Other iPhone browser
'webmate' // Other iPhone browser
));
$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
foreach($agents as $agent) if(strpos($user_agent, $agent)) return TRUE;
return FALSE;
}
?>
Usage
< ?php if(mobileAgent()): ?>
< ?php else: ?>
< ?php endif; ?>