Determining Browser Type with HTTP Headers


Now that you're creating web applications, it's often important to understand the environment you're working inand that includes the browser the user has, which is responsible for displaying what you send it. Different browsers have different capabilities; for example, Internet Explorer has a <MARQUEE> element that no other browser has. And if you don't know whether the user has Internet Explorer, you won't be able to use the <MARQUEE> element. So how can you check what browser the user is using? Check $_SERVER["HTTP_USER_AGENT"]. For example, if the string in this array element contains the text "MSIE" (which you can check with the PHP string function strpos), the user has Internet Explorer. Here's an example, starting with the simple form you see in Example 6-3, phpbrowser.html.

Example 6-3. A simple submittable form, phpbrowser.html
 <HTML>     <HEAD>         <TITLE>Determining Browser Type</TITLE>     </HEAD>     <BODY>         <CENTER>         <H1>Determining Browser Type</H1>         <FORM METHOD="POST" ACTION="phpbrowser.php">         Click the button....         <INPUT TYPE="SUBMIT" VALUE="Submit">         </FORM>         </CENTER>     </BODY> </HTML> 

You can see this HTML page in Figure 6-3. When the user clicks the button, the browser sends all the standard HTTP headers to the server.

Figure 6-3. A submittable form.


In phpbrowser.php, Example 6-4, we check whether the user has Internet Explorer; if so, we display a <MARQUEE> element, and if not, a simple <H1> header.

Example 6-4. Determining browser type, phpbrowser.php
 <HTML>     <HEAD>         <TITLE>Determining Browser Type</TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Determining Browser Type</H1>             <BR>             <?php                 if(strpos($_SERVER["HTTP_USER_AGENT"], "MSIE")){                     echo("<MARQUEE><H1>You're using the Internet                         Explorer</H1></MARQUEE>");                 }                 else {                     echo("<CENTER><H1>You are not using the Internet                         Explorer</H1></CENTER>");                 }             ?>         </CENTER>     </BODY> </HTML> 

The results appear in Figure 6-4, where the marquee text, "You're using the Internet Explorer" is scrolling across the screen.

Figure 6-4. Determining browser type.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net