8.7. Detecting Different Browsers

Problem

You want to generate content based on the capabilities of a user’s browser.

Solution

Use the object returned by get_browser( ) to determine a browser’s capabilities:

$browser = get_browser( );

if ($browser->frames) {
    // print out a frame-based layout
} elseif ($browser->tables) {
    // print out a table-based layout
} else {
    // print out a boring layout
}

Discussion

The get_browser( ) function examines the environment variable $_ENV['HTTP_USER_AGENT'] (set by the web server) and compares it to browsers listed in an external browser capability file. Due to licensing issues, PHP isn’t distributed with a browser capability file. The “Obtaining PHP” section of the PHP FAQ (http://www.php.net/faq.obtaining) lists http://www.cyscape.com/asp/browscap/ and http://www.amrein. com/apps/page.asp?Q=InowDownload as sources for a browser capabilities file, and there is also one at http://asp.net.do/browscap.zip.

Once you download a browser capability file, you need to tell PHP where to find it by setting the browscap configuration directive to the pathname of the file. If you use PHP as a CGI, set the directive in the php.ini file:

browscap=/usr/local/lib/browscap.txt

If you use Apache, you need to set the directive in your Apache configuration file:

php_value browscap "/usr/local/lib/browscap.txt"

Many of the capabilities get_browser( ) finds are shown in Table 8-1. For user-configurable capabilities such as javascript or cookies though, get_browser( ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.