Quick PHP Function #2 : The User Agent

There are lots of ways to grab the browser’s user agent, this is my simple way of doing it, feel free to share your own.

This comes with two options, echo the results or add them to an array set.

 

 

<?php
	/**
	 *
	 * @param string $result
	 * @return boolean If TRUE echo the browsers, else return an array
	 *
	 */
 function the_user_agent($result){

		$ua = strtolower($_SERVER['HTTP_USER_AGENT']);

		if(stripos($ua,'android') !== false) {
			$browser_echo .= " android";
			$browser['android']=1;
		}
		if(stripos($ua,'webkit') !== false) {
			$browser_echo .= " webkit";
			$browser['webkit']=1;
		}
		if(stripos($ua,'mobile') !== false) {
			$browser_echo .= " mobile";
			$browser['mobile']=1;
		}
		if(stripos($ua,'ipad') !== false) {
			$browser_echo .= " ipad";
			$browser['ipad']=1;
		}
		if(stripos($ua,'IE') !== false) {
			$browser_echo .= " ie";
			$browser['ie']=1;
		}
		if(stripos($ua,'firefox') !== false) {
			$browser_echo .= " firefox";
			$browser['firefox']=1;
		}
		if(!$result){
			echo  $browser_echo;
		} else {	
			return $browser;
		}
	}
?>

 

Example usage:

$browser = the_user_agent();

print_r($browser);

// prints something like: 
// Array (
//     [android] = 1
//     [mobile] = 1
//    )

$browser = the_user_agent(true);

echo $browser;

// prints something like: " android mobile"

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *