3

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.

Yacoby
  • 54,544
  • 15
  • 116
  • 120
ron8
  • 243
  • 2
  • 5
  • 13
  • 1
    Are you trying to set which event something gets hooked into in Javascript? If so then don't handle this is PHP. Do the detection in JS. – Dan Apr 17 '10 at 12:15
  • The detection in javacript is fine. I just want to have these two variables set in PHP at the end of the detection. Hope that makes sense. – ron8 Apr 17 '10 at 12:17

4 Answers4

2

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

?>
Sam Becker
  • 19,231
  • 14
  • 60
  • 80
1

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
  • 54,544
  • 15
  • 116
  • 120
  • Okay. But how can I get this query down to the basis to show that the browser is IE or Firefox. Thanks – ron8 Apr 17 '10 at 12:14
  • Sometimes user comments in manual are very helpful http://www.php.net/manual/en/function.get-browser.php#97154 – Michał Mech Apr 17 '10 at 12:16
  • You can only calculate this. You will never be sure. Last thing You can do is to find best regexp query. – Michał Mech Apr 17 '10 at 12:27
  • php.net/manual/en/function.get-browser.php#97154 didn't manage to work. I dont see what is wrong. – ron8 Apr 17 '10 at 12:29
0

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
  • 33,261
  • 11
  • 73
  • 81
0

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
  • 1,481
  • 7
  • 13