Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check Android version from user agent string.
<?php
$str = '~~ Android 2.2.1; ~~';
function get_android_version($str) {
$start = strpos($str, ' Android ');
if ($start === false) {
return '';
}
$remains = substr($str, $start);
$end = strpos($remains, ';');
$remains = substr($remains, 0, $end);
return str_replace(' Android ', '', $remains);
}
function is_supported_android_version($uas) {
$version_string = get_android_version($uas);
echo(strlen($version_string));
if (strlen($version_string) == 0) {
return true;
}
$version = explode('.', $version_string);
$is_supported = true;
if (strlen($version[0]) > 0 && $version[0] < 2) {
$is_supported = false;
}
if (strlen($version[0]) > 0 && strlen($version[1]) > 0 && $version[0] == 2 && $version[1] < 3) {
$is_supported = false;
}
return $is_supported;
}
function tests($str, $result = false) {
if (is_supported_android_version($str) == $result) {
echo('PASS' . "\n");
} else {
echo('FALSE' . "\n");
}
}
tests('~~ Android 2.2.1; ~~');
tests('Mozilla/5.0 (Linux; U; Android 0.5; en-us) AppleWebKit/522+ (KHTML, like Gecko) Safari/419.3');
tests('Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1');
tests('Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17');
tests('Mozilla/5.0 (Linux; U; Android 1.6; en-gb; Dell Streak Build/Donut AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/ 525.20.1');
tests('Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13', true);
tests('', true);
tests('Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30', true);
tests('Mozilla/5.0 (Linux; U; Android 10.4.2.3.4.1.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30', true);
tests('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:12.0) Gecko/20100101 Firefox/12.0', true);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment