PHP Browser Detection
One of our clients – a large retailer – has been seeing an uptick in customer service requests stemming from problems in Apple’s Safari browsers. Back in December 2008 Apple released patch 10.5.6 which broke the way Webkit handles cookies, causing Safari to randomly log out of sites like Facebook and “forget” user baskets. Interestingly, the problem only affects Intel Mac Users.
While we work on the problem enabling our client’s Safari-based customers to place their orders online, we decided on the interim step of warning visitors when they may run into trouble. In order to reach the narrowest target audience and exclude unaffected customers (we don’t want to scare them off) we decided on the following:
1. Show the message only to Safari users
2. Show the message only to Safari users of the Mac OS
3. Show the message only to Safari users running on Intel hardware
I didn’t want to narrow the specific OS version to 10.5.6, because 10.5.7 may not necessary correct the issue (I hope it does).
Checking for the Operating System and Web Browser is dead easy in PHP. At Mergenta, we always use the $_SERVER array to access the server variables superglobal [http://ca2.php.net/manual/en/language.variables.superglobals.php]. Since the contents of the array aren’t guaranteed it is important to check for the existance of the “HTTP_USER_AGENT” member:
$userAgent = ( isset( $_SERVER["HTTP_USER_AGENT"] ) ? $_SERVER["HTTP_USER_AGENT"] : "" );
The user agent gives us a string similar to: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-us) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/3.2.1 Safari/525.27.1
Once we have the userAgent, it’s very simple to check for Mac, Intel and Safari using strpos:
if ( strpos( $userAgent, "Intel Mac" ) !== false
&& strpos( $userAgent, "Safari" ) !== false )
{
// Display message to Intel Mac Safari users here
}
Note that we use the “===” operator (3 equal signs) to figure out whether or not the “needle” was found in the “haystack”. This is because while strpos returns integers to indicate where in the haystack it finds the needle, it also returns the boolean FALSE when no match is found. “===” checks for the boolean result FALSE, not to be confused with “0″ which strpos might return to indicate a match was found at the beginning of the haystack.