Creating a Simple Input Form
For now, let's keep our HTML separate from our PHP code. Listing 9.1 builds a simple HTML form.
Listing 9.1 A Simple HTML Form
1: <html>
2: <head>
3: <title>Listing 9.1 A simple HTML form</title>
4: </head>
5: <body>
6: <form action="listing9.2.php" method="POST">
7: <p><strong>Name:</strong><br>
8. <input type="text" name="user"></p>
9: <p><strong>Address:</strong><br>
10. <textarea name="address" rows="5" cols="40"></textarea></p>
11: <p><input type="submit" value="send"></p>
12: </form>
13: </body>
14: </html>
Put these lines into a text file called listing9.1l, and place that file in your Web server document root. This listing defines a form that contains a text field with the name "user" on line 8, a text area with the name "address" on line 10, and a submit button on line 12. The FORM element's ACTION argument points to a file called listing9.2.php, which processes the form information. The method of this form is POST, so the variables are stored in the $_POST superglobal.Listing 9.2 creates the code that receives our users' input.
Listing 9.2 Reading Input from a Form
1: <html>
2: <head>
3: <title>Listing 9.2 Reading input from a form </title>
4: </head>
5: <body>
6: <?php
7: echo "<p>Welcome <b>$_POST[user]</b></p>";
8: echo "<p>Your address is:<br><b>$_POST[address]</b></p>";
9: ?>
10: </body>
11: </html>
Put these lines into a text file called listing9.2.php, and place that file in your Web server document root. Now access the form itself with your Web browser, and you should see something like Figure 9.1.
Figure 9.1. Form created in Listing 9.1.

The script in Listing 9.2 is the first script in this book that isn't designed to be called by clicking a link or typing directly into the browser's location field. Instead, this file is called when a user submits the form created in Listing 9.1.In the code, we access two variables: $_POST[user] and $_POST[address]. These are references to the variables in the $_POST superglobal, which contain the values that the user entered in the user text field and the address text area. Forms in PHP really are as simple as that.Enter some information in the form fields, and click the send button. You should see your input echoed to the screen.
![]() | You could also use the GET method in this form (and others). POST can handle more data than GET and does not pass the data in the query string. If you use the GET method, be sure to change your superglobal to $_GET and not $_POST. |