How to determine the browser of the user using PHP?

655 Views Asked by At

How to determine the browser of the user using PHP?

So that if the users browser is IE then the variable $alert="onbeforeunload" and if it is not IE, for example Firefox (else) then $alert="onload.

Help is much appreciated.

Thanks

Also please note that I can not install browscap.ini on my PHP server.

4

There are 4 best solutions below

0
On BEST ANSWER

See if this code works for you

<?php
function detect_ie(){
    return (sizeof(explode("MSIE",$_SERVER['HTTP_USER_AGENT'])) > 1);
}

if (detect_ie())
    $event = "onbeforeunload";
else
    $event = "onload";

?>
0
On

use $_SERVER['HTTP_USER_AGENT']

Check if it contains "IE" directly followed by a number.

I'd rather do this in javascript itself though.

if (typeof window.onbeforeunload !== "undefined") window.onbeforeunload = myFunc;
else window.onunload = myFunc;
4
On

You can't. Not with 100% accuracy. The best method that is to check the user agent, however the user is free not to supply it, or fake it so try to avoid relying on it.

$ua = $_SERVER['HTTP_USER_AGENT'];

If the browser is IE, it should (roughtly) match (Where # is a number)

Mozilla/#.0 (compatible;  MSIE #.##;

For which the regex would be something like

'~^Mozilla/[0-9]\.0 (compatible;\s+MSIE~i'

Alternatively you could just check for the string "MSIE" which would be simpler and slightly less strict.

But as @Michal said, there are other (better) implmentations on the get_browser manual page

0
On

Javascript libraries are much better to detect and handle different browser behaviour. Just let a mature library like jQuery handle this and you'll be fine.