PHP - User Agent

From XennisWiki
Jump to: navigation, search

Get the browser information of a user with PHP.

Ausführliche Hilfe: get_browser

<?php
// Print user-agent
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?>

Browser-Erkennung

<?php
/**
 * Gibt Informationen über den Browser zurück
 *	(string)  id:        Kurname (z.b. msie)
 *	(string)  version:   Versionsnummer
 *	(string)  name:      Name (z.B. Windows Internet Explorer)
 *	(string)  site:      Link zur offizielle Seite
 *	(string)  version_l: Aktuellste Versionsnummer
 *	(boolean) old:       Ob der Browser veraltet ist, oder nicht
 *
 * @return array $browser Siehe Oben
 */
function getBrowser()
{
	$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	$known = array ('opera', 'chrome', 'msie', 'safari', 'firefox');
	$browser = array('id' => 'unknown', 'version' => 'unknown', 'name' => 'Unknown', 'site' => '', 'version_l' => '', 'old' => 'false');

	$info = getBrowserAll();

	// name
	for($i = 0; $i < count($known); $i++) {
		if(preg_match('/'.$known[$i].'/i', $agent)) {
			$browser['id'] = $known[$i];
			break;
		}
	}

	if($browser['id'] != 'unknown') {

		// version
		$search =  array ('version/', $browser['id'].'/', $browser['id'].' ');

		for($i = 0; i < count($search); $i++) {	

			$version = strstr($agent, $search[$i]);
			$version = strstr($version, '.', true);
			$version = str_replace($search[$i], '', $version);

			if($version != '') {
				$browser['version'] = $version;
				break;
			}
		}

		// info
		$browser['name'] = $info[$browser['id']]['name'];
		$browser['site'] = $info[$browser['id']]['site'];
		$browser['version_l'] = $info[$browser['id']]['version'];

		if($browser['version'] < $browser['version_l']) {
			$browser['old'] = 'true';	
		}
	}

	return $browser;
}

/**
 * Gibt Informationen über alle Browser zurück
 *
 * @return array $getBrowserAll
 */
function getBrowserAll()
{

	$getBrowserAll = array(
		'chrome' => array(
			'name' => 'Google Chrome',
			'site' => 'google.com/chrome',
			'version' => '16'
		),
		'firefox' => array(
			'name' => 'Mozilla Firefox',
			'site' => 'firefox.com',
			'version' => '10'
		),
		'msie' => array(
			'name' => 'Windows Internet Explorer',
			'site' => 'microsoft.com/windows/internet-explorer',
			'version' => '9'
		),
		'opera' => array(
			'name' => 'Opera',
			'site' => 'opera.com',
			'version' => '11'
		),
		'safari' => array(
			'name' => 'Safari',
			'site' => 'apple.com/safari',
			'version' => '5'
		)
	);

	return $getBrowserAll;
}
?>

See also

External links