views:

91

answers:

5

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.

A: 

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;
Tor Valamo
+1  A: 

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

Yacoby
Okay. But how can I get this query down to the basis to show that the browser is IE or Firefox. Thanks
ron8
Sometimes user comments in manual are very helpful http://www.php.net/manual/en/function.get-browser.php#97154
Michał Mech
You can only calculate this. You will never be sure. Last thing You can do is to find best regexp query.
Michał Mech
php.net/manual/en/function.get-browser.php#97154 didn't manage to work. I dont see what is wrong.
ron8
A: 

This could help: http://php.net/manual/en/function.get-browser.php

Haluk
You should really read this first. @ron8 said that, he can't use browscap.ini
Michał Mech
+2  A: 

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";

?>
Sam152
Tried it and works great.Your a legend.
ron8
No problemo Ron.
Sam152
A: 

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.

elias