Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

672 LESSON 24: Taking Advantage of the Server


the form using a built-in PHP variable that returns the URL for the page currently being
displayed. That way I can make sure the form is submitted to itself without including the
URL for the page in my HTML. Here’s the basic structure of the page:
<?php
// Form processing code
?><!doctype html>
<html>
<head>
<title>Page Structure</title>
<style>
/* Page styles go here. */
</style>

</head>
<body>
<h1>Sample Page</h1>
<!-- Print form errors here -->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_
SELF"]);?>">
<!-- Present form fields here -->
</form>
</body>
</html>

This structure is pretty common for pages that present a form and process that form, too.
The PHP processor runs the scripts on the page from top to bottom, so all the form pro-
cessing will take place before any of the page is presented. If this page were going to do
more than just validate the form, it would probably redirect the user to a page thanking
him or her for registering if the validation code found no errors. It would also probably
save the values submitted through the form somewhere. In this case, though, I’m just
explaining form validation.
As you can see, the form-processing code lives on the same page as the form itself, so the
form will be submitted to this page. The validation code will live within the script section
at the top of the page. My objective for this page is to make sure that the user enters all
the required data and that the age the user enters is actually a number.
The first thing I need to do is initialize my PHP and define my variables. I need to set
variables for all my form fields and their error messages, as well as the array of toys:
// define variables
$nameErr = $ageErr = $toysErr = $errors = "";
$name = $age = "";
$toys = array();


Free download pdf