Example 4 - Reading Form Data
PHP is well-suited for reading information from Web forms. Example 4 reads input from a sample Web form and uses it to create a Web page based on the input. Specifically, the form asks the user for his or her name, year of birth, and favorite color. Upon reading this information from the form, the PHP script will display a page with the person's name, their age, and a background in their favorite color.
<HTML> <HEAD> <TITLE> Example 4 </TITLE> </HEAD> <? // Initialize variables from form $name = $_POST['name']; $favcolor = $_POST['favcolor']; $yearborn = $_POST['yearborn']; // encode any special characters in these variables $encoded_name = htmlentities($name); $encoded_favcolor = htmlentities($favcolor); // print the body tag containing the person's favorite color // as a background print("<body bgcolor=$encoded_favcolor>"); // print the person's name print("Hello $encoded_name<br>"); // Get the current date and store it in $currentdate, an array // Retrieve the year from the $currentdate array and store it in // a variable called $year, this will be used in calculating the age $currentdate = getdate(); $year = $currentdate["year"]; // Calculate age using the $yearborn field from the submitted form $age = $year - $yearborn; // print the person's age print("You are $age years old"); ?> </BODY> </HTML>
Let's take a closer look at the code. The first thing to note is that PHP can output anything you want, including HTML. In this case we print out the HTML <BODY> tag from our PHP script because we are reading the background color from the submitted Web form. Form fields are accessed in your PHP script as variables, $_POST[fieldname] or $_GET[fieldname] (depending on the request method), where fieldname is the name of an input field from the Web form. In this case the favcolor field from the Web form is the $_POST['favcolor'] variable in PHP. For convenience, it's common practice to assign these values to shorter variables names in your script.
The next important step is to clean the input from the form. Users can input special characters in your code that can be used in cross site scripting or other attacks. The htmlentities() function in PHP will escape many of these special characters so they are benign. It's good practice to never trust input you get from a Web form. Check it, and process it before you commit it to a database or send it back as output.
In addition to variables from form fields and environment variables, you can create your own variables in PHP. We create a variable called $year and an array called $currentdate. The notation for an array is similar to a variable (they both begin with the $ character), but arrays contain multiple values.
The $_POST[name] and $_POST[yearborn] variables come from the submitted form.