Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

A Script to Acquire User Input

For now, we'll keep our HTML separate from our PHP code. Listing 9.2 builds a simple HTML form.

Listing 9.2 A Simple HTML Form

 1: <html>
 2: <head>
 3: <title>Listing 9.2 A simple HTML form</title>
 4: </head>
 5: <body>
 6: <form action="listing9.3.php">
 7: <input type="text" name="user">
 8: <br>
 9: <textarea name="address" rows="5" cols="40">
10: </textarea>
11: <br>
12: <input type="submit" value="hit it!">
13: </form>
14: </body>
15: </html>

We define a form that contains a text field with the name "user" on line 7, a text area with the name "address" on line 9, and a submit button on line 12. It is beyond the remit of this book to cover HTML in detail. If you find the HTML in these examples hard going, take a look at Sams Teach Yourself HTML in 24 Hours or one of the numerous online HTML tutorials. The FORM element's ACTION argument points to a file called listing9.3.php, which processes the form information. Because we haven't added anything more than a filename to the ACTION argument, the file listing9.3.php should be in the same directory on the server as the document that contains our HTML.

Listing 9.3 creates the code that receives our users' input.

Listing 9.3 Reading Input from the Form in Listing 9.2

 1: <html>
 2: <head>
 3: <title>Listing 9.3 Reading input from the form in Listing 9.2</title>
 4: </head>
 5: <body>
 6: <?php
 7: print "Welcome <b>$user</b><P>\n\n";
 8: print "Your address is:<P>\n\n<b>$address</b>";
 9: ?>
10: </body>
11: </html>

This is the first script in this book that is not designed to be called by hitting a link or typing directly into the browser's location field. We include the code from Listing 9.3 in a file called listing9.3.php. This file is called when a user submits the form defined in Listing 9.2.

In the code, we have accessed two variables, $user and $address. It should come as no surprise that these variables contain the values that the user added to the text field named "user" and the text area named "address". Forms in PHP really are as simple as that. Any information submitted by a user will be available to you in global variables that will have the same names as those of the form elements on an HTML page.

  • + Share This
  • 🔖 Save To Your Account