HTML and CSS Reference
In-Depth Information
<h1> Sample Page </h1>
<!— Print form errors here —>
<form method=”post” action=”<?= $_SERVER['PHP_SELF'] ?>”>
<!— Present form fields here —>
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
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. To make
things a bit easier on myself, I've written a function to do the actual validation for me.
Here's the function:
function validate() {
$errors = array();
if (empty($_POST['name'])) {
$errors['name'] = 'You must enter your name.';
if (!is_numeric($_POST['age'])) {
$errors['age'] = “You must enter a valid age.”;
if (empty($_POST['toys'])) {
$errors['toys'] = 'You must choose at least one toy.';
return $errors;
This function validates each of the fields on the form and then places all the errors in an
associative array called $errors . When an error is detected, a new entry is added to the
Search WWH ::

Custom Search