WP-Mix

A fresh mix of code snippets and tutorials

PHP Detect All Versions of IE

Quick code snippet for detecting all versions of good ’ol IE (Internet Explorer).

Using PHP’s preg_match(), it is possible to match all versions of IE. Consider the following example:

$ua = htmlentities($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8');
if (preg_match('~MSIE|Internet Explorer~i', $ua) || (strpos($ua, 'Trident/7.0; rv:11.0') !== false)) {
	// do stuff for IE
}

Here we are sanitizing the user agent and storing it as a variable named $ua. We then use preg_match() to pattern-match for IE 10 and below (first “or” condition) and also IE 11 (second “or” condition). Cumulatively this accounts for all currently existing versions of Internet Explorer.

Remember to update this technique with the advent of future versions of IE!

Update!

Some versions of IE now add “Touch” to the user agent string, for example:

Trident/7.0; Touch; rv:11.0

So to account for the possible Touch variable, we update the original code like so:

$ua = htmlentities($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8');
if (preg_match('~MSIE|Internet Explorer~i', $ua) || (strpos($ua, 'Trident/7.0') !== false && strpos($ua, 'rv:11.0') !== false)) {
	// do stuff for IE
}

This result is the same, but now covers Touch cases as well.

Thanks to Dan for this tip!

★ Pro Tip:

USP ProSAC Pro