Listening Video
Learn how to program arrays in PHP at a basic enough level to make an efficient user agent sniff script. We use a foreach loop to run the evaluation needed for finding a match in the user agent string.
COPY + PASTE VERSION - http://sh.st/aqisN
Be sure to view the video guide below documenting creation of this file for full understanding.
COPY + PASTE VERSION - http://sh.st/aqisN
Be sure to view the video guide below documenting creation of this file for full understanding.
<?php
/* ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ */
/* Script written by Adam Khoury at www.developphp.com */
/* VIDEO GUIDE - http://www.developphp.com/view.php?tid=1057 */
/* See video guide above for full explanation if you want full understanding */
/* ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ */
// Obtain user agent which is a long string not meant for human reading
$agent = $_SERVER['HTTP_USER_AGENT'];
// Get the user Browser now -----------------------------------------------------
// Create the Associative Array for the browsers we want to sniff out
$browserArray = array(
'Windows Mobile' => 'IEMobile',
'Android Mobile' => 'Android',
'iPhone Mobile' => 'iPhone',
'Firefox' => 'Firefox',
'Google Chrome' => 'Chrome',
'Internet Explorer' => 'MSIE',
'Opera' => 'Opera',
'Safari' => 'Safari'
);
foreach ($browserArray as $k => $v) {
if (preg_match("/$v/", $agent)) {
break;
} else {
$k = "Browser Unknown";
}
}
$browser = $k;
// -----------------------------------------------------------------------------------------
// Get the user OS now ------------------------------------------------------------
// Create the Associative Array for the Operating Systems to sniff out
$osArray = array(
'Windows 98' => '(Win98)|(Windows 98)',
'Windows 2000' => '(Windows 2000)|(Windows NT 5.0)',
'Windows ME' => 'Windows ME',
'Windows XP' => '(Windows XP)|(Windows NT 5.1)',
'Windows Vista' => 'Windows NT 6.0',
'Windows 7' => '(Windows NT 6.1)|(Windows NT 7.0)',
'Windows NT 4.0' => '(WinNT)|(Windows NT 4.0)|(WinNT4.0)|(Windows NT)',
'Linux' => '(X11)|(Linux)',
'Mac OS' => '(Mac_PowerPC)|(Macintosh)|(Mac OS)'
);
foreach ($osArray as $k => $v) {
if (preg_match("/$v/", $agent)) {
break;
} else {
$k = "Unknown OS";
}
}
$os = $k;
// At this point you can do what you wish with both the OS and browser acquired
echo '<h1>PHP Tutorial : Get User Browser and Operating System Using Arrays</h1>';
echo $agent;
echo "<h2>You are using: <em>$browser - $os</em></h2>";
?>
0 Response to "Learn PHP Array Programming for User Agent Script : Get User Browser and OS"
Post a Comment