Finding part of a Variable..

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
GodsDead
Forum Newbie
Posts: 1
Joined: Sat Nov 05, 2005 9:31 am
Location: Clacton - on -sea
Contact:

Finding part of a Variable..

Post by GodsDead »

<?php
echo"$HTTP_USER_AGENT";
?>
Useing that, how can i select the browser name so it just Echos out the Browser name?
E.g.

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.7.12) Gecko/20050919 Firefox/1.0.7

*Bit in red.

Or select the Windows Operating System..
Xp Home Etc..[/b]
User avatar
mchaggis
Forum Contributor
Posts: 150
Joined: Mon Mar 24, 2003 10:31 am
Location: UK

Post by mchaggis »

There is no "easy" way as each browser passes it's own variant of formatting for the USER_AGENT string.

However, the following code could be used as a base:

Code: Select all

// Define the Browser Detection strings
$DetectionRegs = Array(
        'MSIE'     => '^Mozilla.+MSIE ([0-9\.]+);',
        'Netscape' => '^Mozilla.+Netscape.([0-9\.]+)',
        'Mozilla' => '^Mozilla.+rv:([0-9\.]+)',
        'Gecko'    => '^Mozilla.+Gecko.([0-9\.]+)',
        'Firebird' => 'Firebird.([0-9\.]+)?',
        'Firefox'  => 'Firefox.([0-9\.]+)?'
);

foreach (  $DetectionRegs as $Browser => $BrowserReg ) {
        if (eregi($BrowserReg, $_SERVER['HTTP_USER_AGENT'], $matches) ) {
                // We have a match, so just set the variables and quit the loop
                $BrowserMatch   = $Browser; // Just incase 
                $BrowserVersion = $matches[1];
                break;
        }
}

print "This is Browser: $BrowserMatch Version: $BrowserVersion";
Apart from 1 or 2 typo's that may have slipped in, that should do you. If any browsers are not listed, then adding an additional regexp to the list will work.
TJ
Forum Newbie
Posts: 20
Joined: Thu Nov 03, 2005 10:22 pm
Location: Nottingham, UK

Post by TJ »

The kind of functionality you describe is commonly called browser sniffing or browser caps aka browser capabilities. There'll be libraries around that do that to varying degrees of sophistication.

I've written my own limited code for detecting a specific (non-web) client using a regular expression, but that won't be suitable for the case you have.

Try Googling for PHP "browser caps" detect and see where that leads.
niceguyeddie
Forum Newbie
Posts: 13
Joined: Fri Nov 28, 2003 7:12 am
Location: Westminster, MD

Post by niceguyeddie »

User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

TJ's last comment was referring to get_browser(), at least indirectly :)
Post Reply