Part III: Start with Simple Stuff
Chapter 7: Displaying Dynamic Content
Chapter 8: Sending E-Mail
Chapter 9: Using Your File System
Chapter 10: Uploading Files to Your Web Site
Chapter 7: Displaying Dynamic Content
Overview
The Web is a dynamic environment, so why not use your programming skills to display dynamic content? Dynamic content can be as simple or as complex as you want it to be. In this chapter, you'll learn how to do the following:
• Display browser-specific HTML
• Display platform-specific HTML
• Use PHP string functions on HTML form input
• Create a redirection menu using an HTML form and the header() function Displaying Browser-Specific HTML
In the previous chapter, you learned to retrieve and print the HTTP_USER_AGENT environment variable to the screen. In this chapter, you'll do something a bit more interesting with the value of HTTP_USER_AGENT, and that's to print browser-specific HTML.
However, having seen some of the possible values of HTTP_USER_AGENT in the last chapter, you can imagine that there are hundreds of slightly different values. So it's time to learn some basic pattern matching.
You'll use the preg_match() function to perform this task. This function needs two arguments: what you're looking for, and where you're looking:
preg_match("/[what you're looking for]/", "[where you're looking]");
This function will return a value of true or false, which you can use in an if…else block to do whatever you want. The goal of the first script is to determine if a Web browser is Microsoft Internet Explorer, Netscape, or something else. This can be a little tricky, but not because of PHP.
Within the value of HTTP_USER_AGENT, Netscape always uses the string Mozilla to identify itself. Unfortunately, the value of HTTP_USER_AGENT for Microsoft Internet Explorer also uses Mozilla to show that it's compatible. Luckily, it also uses the string MSIE, so you can search for that. If the value of HTTP_USER_AGENT doesn't contain either Mozilla or MSIE, chances are very good that it's not one of those Web browsers.
1. Open a new file in your text editor and start a PHP block, then use getenv() to place the value of HTTP_USER_AGENT in a variable called $agent:
2. <?
3. $agent = getenv("HTTP_USER_AGENT");
4. Start an if…else statement to find which of the preg_match() functions is true, starting with the search for MSIE:
5. if (preg_match("/MSIE/i", "$agent")) {
6. $result = "You are using Microsoft Internet Explorer.";
7. } 8.
9. Continue the statement, testing for Mozilla:
10. else if (preg_match("/Mozilla/i", "$agent")) { 11. $result = "You are using Netscape.";
12. }
13. Finish the statement by defining a default:
14. else {
15. $result = "You are using $agent";
16. } 17.
Note The i in the preg_match() function performs a case-insensitive search.
18. Close your PHP block and add some HTML to begin the display:
19. ?>
20. <HTML>
21. <HEAD>
22. <TITLE>Browser Match Results</TITLE>
23. </HEAD>
24. <BODY>
25. Type the following PHP code to print the result of the if…else statement:
26. <? echo "<P>$result</P>"; ?>
27. Add some more HTML so that the document is valid:
28. </BODY>
29. </HTML>
30. Save the file with the name browsermatch.php and place this file in the document root of your Web server.
31. Open your Web browser and type http://127.0.0.1/browsermatch.php
The Browser War rages on: no one Web browser is used by a vast majority of Web surfers. Various versions of Microsoft Internet Explorer (MSIE) account for approximately 78 percent of Web browsers in use, while versions of Netscape (NS) take up about 15 percent. Throw in the die-hard Lynx, Opera, Konquerer, and other users to reach 100 percent.
Although an 80/20 split might seem like a majority, if 500 million people have access to the Internet, 100 million non-Microsoft users is a huge number of users to consider when developing a good Web site. HotWired maintains a browser reference at
http://hotwired.lycos.com/webmonkey/reference/browser_chart/. This chart shows you some of the differences between the major browsers. In the next section, you'll take into consideration how not all platforms are created equal, and in fact do not display HTML the same either.
Displaying Platform-Specific HTML
There are differences not only between browsers, but also between platforms. This difference is most clear with regard to fonts and font sizes. In the Windows world, you have fonts such as Times New Roman and Courier New. Slight variations of these fonts appear on the Macintosh and Linux/UNIX platforms; they are called Times and Courier. It doesn't end there—the font sizes all display differently. A 10-point font on Macintosh or Linux is sometimes barely legible, but if you bump it up to 11 or 12 point, you're in business. If that same 12-point font is viewed on Windows, however, it might look like your text is trying to take over the world.
So what to do? Use your new pattern-matching skills to extract the platform from the HTTP_USER_AGENT string, and then display platform-specific HTML. As with matching on a keyword—which you did in the previous section—to nail down the platform you need to know what you're looking for. In the next script, you'll check for the keywords "Win" and "Linux" and print an appropriate style sheet block in your HTML result page.
1. Open a new file in your text editor, start a PHP block, and use getenv() to place the value of HTTP_USER_AGENT in a variable called $agent:
2. <?
3. $agent = getenv("HTTP_USER_AGENT");
4. Start an if…else statement to find which of the preg_match() functions is true, starting with the search for "Win":
5. if (preg_match("/Win/i", "$agent")) { 6. $style = "win";
7. }
8. Continue the statement, testing for "Linux":
9. else if (preg_match("/Linux/i", "$agent")) {
10. $style = "linux";
11. } 12.
13. Create a basic style sheet block for Windows users:
14. $win_style = "
15. <style type=\"text/css\">\n
16. p, ul, ol, li{font-family:Arial;font-size:10pt;font- 17. weight:normal;}\n
18. h1 {font-family:Arial;font-size:16pt;font-weight:bold;}\n 19. h2 {font-family:Arial;font-size:14pt;font-weight:bold;}\n 20. strong{font-family:Arial;font-size:10pt;font-weight:bold;}\n 21. em {font-family:Arial;font-size:10pt;font-style:italic;}\n 22. </style>
23. ";
24.
Note When you use quotation marks inside other quotation marks, the inner pair must be delineated from the outside pair using the escape (\) character (also known as a backslash).
25. Create a basic style sheet block for Linux users:
26. $linux_style = "
27. <style type=\"text/css\">\n
28. p, ul, ol, li{font-family:Times;font-size:12pt;font- 29. weight:normal;}\n
30. h1 {font-family:Times;font-size:18pt;font-weight:bold;}\n 31. h2 {font-family:Times;font-size:16pt;font-weight:bold;}\n 32. strong{font-family:Times;font-size:12pt;font-weight:bold;}\n 33. em {font-family:Times;font-size:12pt;font-style:italic;}\n 34. </style>
35. ";
36.
Note The use of the new line (\n) character ensures that your code will print on multiple lines. This is helpful when you are viewing your HTML source.
37. Close your PHP block and add the following HTML:
38. ?>
39. <HTML>
40. <HEAD>
41. <TITLE>Platform Matching</TITLE>
42. Type the following PHP code, creating an if…else statement used to print the correct style sheet block:
43. <?
50. Close the top section of your HTML and start the body:
51. </HEAD>
52. <BODY>
53. Type the following HTML to show the use of your style sheet:
54. <h1 align=center>This is a level 1 heading</h1>
55. <h2 align=center>Look! A level 2 heading</h2>
56. <P align=center>This is a simple paragraph with some 57. <strong>bold</strong> and <em>emphasized</em> text.</P>
58. Add some more HTML so that the document is valid:
59. </BODY>
60. </HTML>
61. Save the file with the name platformmatch.php and place it in the document root of your Web server.
62. Open your Web browser and type http://127.0.0.1/platformmatch.php
You can see that the proper style sheet block was printed, based on the result of the platform match. In the next section, you'll move away from pattern matching and work with some of the string functions in PHP to modify form input before displaying it back to the browser.
Working with String Functions
Numerous string functions are built into PHP, all of which are designed to make your life easier. Suppose you have to normalize strings for news headlines or product ID numbers, or calculate the length of a string before trying to stuff it into a database field. Those are just a few of the string functions you'll learn about in the next section.
For more string functions, take a look at the PHP manual at
http://www.php.net/manual/. The function list seems to grow daily as more people contribute to the language.
Creating an Input Form
In this section, you'll create the front end to a string modification script. This form will contain one text area and several radio buttons. The radio buttons will determine the string function to use.
1. Open a new file in your text editor and type the following HTML:
2. <HTML>
3. <HEAD>
4. <TITLE>Generic Input Form</TITLE>
5. </HEAD>
6. <BODY>
7. Begin your form. Assume that the method is POST and the action is a script called display_input.php:
8. <FORM METHOD="POST" ACTION="display_input.php">
9. Create a text area with a text label:
10. <P><strong>Text Field:</strong><br>
11. <TEXTAREA NAME="text1" COLS=45 ROWS=5 WRAP=virtual></TEXTAREA></P>
12. Add this block of radio buttons:
13. <P><strong>String Function:</strong><br>
14. <INPUT TYPE="radio" NAME="func" VALUE="md5" checked> get md5<br>
15. <INPUT TYPE="radio" NAME="func" VALUE="strlen"> get length of 16. string<br>
17. <INPUT TYPE="radio" NAME="func" VALUE="strrev"> reverse the 18. string<br>
19. <INPUT TYPE="radio" NAME="func" VALUE="strtoupper"> make string 20. uppercase<br>
21. <INPUT TYPE="radio" NAME="func" VALUE="strtolower"> make string 22. lowercase<br>
23. <INPUT TYPE="radio" NAME="func" VALUE="ucwords"> make first letter 24. of all words uppercase</P>
25.
Note The value for each option button is its exact PHP function name. This will make the back-end script very simple to create, as you'll see in the next section.
26. Add a submit button:
27. <P><INPUT TYPE="submit" NAME="submit" VALUE="Do Something With the 28. String"></P>
29.
30. Close your form and add some more HTML so that the document is valid:
31. </FORM>
32. </BODY>
33. </HTML>
34. Save the file with the name generic_form.html and place this file in the document root of your Web server.
35. Open your Web browser and type http://127.0.0.1/generic_form.html
Creating a Script to Display Form Values
According to the form action in generic_form.html, you need a script called
display_input.php. The goal of this script is to accept the text in $_POST[text1] and use a particular string function (the value of $_POST[func]) to get a new result ($result).
1. Open a new file in your text editor and type the following PHP:
2. <? $result = $_POST[func]($_POST[text1]); ?>
3. Start the HTML output:
4. <HTML>
5. <HEAD>
6. <TITLE>Generic Input Results</TITLE>
7. </HEAD>
8. <BODY>
9. Display the value of $result:
10. <? echo "$result"; ?>
11.
12. Add a link back to the form:
13. <P><a href="generic_form.html">Go again!</a></P>
14. Add some more HTML so that the document is valid:
15. </BODY>
16. </HTML>
17. Save the file with the name display_input.php and place this file in the document root of your Web server.
In the next section, you'll submit the form and see all these different types of string functions at work.
Submitting Your Form and Getting Results
Now that you've created both a front-end form and a back-end script, it's time to try them out.
1. Open your Web browser and type http://127.0.0.1/generic_form.html 2. Type the following text in the text area:
I think PHP is just the coolest server-side scripting language around!
Who knew it would be this simple?
Note You might want to copy that chunk of text to the Clipboard because it will be used in all of the following examples.
3. Select the get md5 radio button, and click on the Do Something With The String button.
Note The md5() function gets a hash of the string. A hash is like a digital summary of the string. It can be used to compare versions of strings (or files) to see if the versions differ.
1. Click on the Go again! link.
2. Enter the same text in the text area:
I think PHP is just the coolest server-side scripting language around!
Who knew it would be this simple?
3. Select the get length of string radio button.
4. Click on the Do Something With The String button.
1. Click on the Go again! link.
2. Enter the same text in the text area:
I think PHP is just the coolest server-side scripting language around!
Who knew it would be this simple?
3. Select the reverse the string radio button.
4. Click on the Do Something With The String button.
1. Click on the Go again! link.
2. Enter the same text in the text area:
I think PHP is just the coolest server-side scripting language around!
Who knew it would be this simple?
3. Select the make string uppercase radio button.
4. Click on the Do Something With The String button.
1. Click on the Go again! link.
2. Enter the same text in the text area:
I think PHP is just the coolest server-side scripting language around!
Who knew it would be this simple?
3. Select the make string lowercase radio button.
4. Click on the Do Something With The String button.
1. Click on the Go again! link.
2. Enter the same text in the text area:
I think PHP is just the coolest server-side scripting language around!
Who knew it would be this simple?
3. Select the make first letter of all words uppercase radio button.
4. Click on the Do Something With The String button.
To add some error checking to your script, check for the value of $_POST[func] as well as the value of $_POST[text1] before any other action occurs. Replace your first block of PHP code with this:
<?
if (($_POST[func] == "") || ($_POST[text1] == "")){
header("Location: http://127.0.0.1/generic_form.html");
exit;
}
$result = $_POST[func]($_POST[text1]);
?>
Now if some rogue user directly accesses the script without using the form, he'll be redirected back to the form, and no errors will occur.
Redirecting to a New Location
Redirecting a user to a new location means that your script has sent an HTTP header to the browser, indicating a new location. HTTP headers of any kind (authentication, redirection, cookies, and so on) must be sent to the browser before anything else, including white space, line breaks, and any characters.
In the next section, you'll create a redirection menu and a redirection form. The goal is to have the user select a new location from the menu and then have the script automatically send him there.
Creating a Redirection Form
In this section, you'll create the front end to a redirection script. This form will contain a drop-down list of the names of various Web sites. The value for each option is the Web site's URL.
1. Open a new file in your text editor and type the following HTML:
2. <HTML>
3. <HEAD>
4. <TITLE> Redirection Menu</TITLE>
5. </HEAD>
6. <BODY>
7. Begin your form. Assume that the method is POST and the action is a script called do_redirect.php:
8. <FORM METHOD="POST" ACTION="do_redirect.php">
9. Add this drop-down list:
10. <P>Send me to:
11. <SELECT name="location">
12. <OPTION value="http://www.premierpressbooks.com/">Premier 13. Press</OPTION>
14. <OPTION value="http://www.thickbook.com/">thickbook.com 15. </OPTION>
16. <OPTION value="http://www.i2ii.com/">i2i Interactive</OPTION>
17. <OPTION value="http://www.php.net/">PHP.net</OPTION>
18. <OPTION value="http://www.zend.com/">Zend Technologies</OPTION>
19. </SELECT>
20. Add a submit button:
21. <P><INPUT TYPE="submit" NAME="submit" VALUE="Go!"></P>
22. Close your form, and add some more HTML so that the document is valid:
23. </FORM>
24. </BODY>
25. </HTML>
26. Save the file with the name redirect_form.html and place this file in the document root of your Web server.
27. Open your Web browser and type http://127.0.0.1/redirect_form.html
In the next section, you'll create the backend script. That script will expect one variable: $_POST[location].
Creating the Redirection Script and Testing It
According to the form action in redirect_form.html, you need a script called
do_redirect.php. The goal of this script is to accept the value of $_POST[location]
and print that value within the header() function so that the user is redirected to the chosen location.
1. Open a new file in your text editor and type the following PHP to create the proper redirection header:
2. <?
3. header( "Location: $_POST[location]");
4. exit;
5. ?>
6.
7. Save the file with the name do_redirect.php and place this file in the document root of your Web server.
8. Open your Web browser and type http://127.0.0.1/redirect_form.html 9. Select Premier Press from the drop-down list, and click on the Go! button.
Users will now be redirected to the Premier Press Web site.
To add some error checking to your script, check for the value of $_POST[location]
before trying to do the redirection. Replace your PHP code with this:
<?
if ($_POST[location] == "") {
header("Location: http://127.0.0.1/redirect_form.html");
exit;
} else {
header("Location: $_POST[location]");
exit;
}
?>
Now if a user directly accesses the script, he'll be redirected back to the form, and no errors will occur.