Source<?php # Script 2.4 - form processing with error handling
//check if form has been submitted
$sent = (isset($_REQUEST['submit']))?$_REQUEST['submit']:null;
if($sent) {
// Validate the name:
if (!empty($_REQUEST['name'])) {
$name = $_REQUEST['name'];
} else {
$name = NULL;
echo '<p class="error">You forgot to enter your name!</p>';
}
// Validate the email:
if (!empty($_REQUEST['email'])) {
$email = $_REQUEST['email'];
} else {
$email = NULL;
echo '<p class="error">You forgot to enter your email address!</p>';
}
// Validate the comments:
if (!empty($_REQUEST['comments'])) {
$comments = $_REQUEST['comments'];
} else {
$comments = NULL;
echo '<p class="error">You forgot to enter your comments!</p>';
}
// Validate the gender:
if (isset($_REQUEST['gender'])) {
$gender = $_REQUEST['gender'];
if ($gender == 'M') {
$greeting = '<p><b>Good day, Sir!</b></p>';
} elseif ($gender == 'F') {
$greeting = '<p><b>Good day, Madam!</b></p>';
} else { // Unacceptable value.
$gender = NULL;
echo '<p class="error">Gender should be either "M" or "F"!</p>';
}
} else { // $_REQUEST['gender'] is not set.
$gender = NULL;
echo '<p class="error">You forgot to select your gender!</p>';
}
// If everything is OK, print the message:
if ($name && $email && $gender && $comments) {
echo "<p>Thank you, <b>$name</b>, for the following comments:<br />
<tt>$comments</tt></p>
<p>We will reply to you at <i>$email</i>.</p>\n";
echo $greeting;
} else { // Missing form value.
echo '<p class="error">Please go back and fill out the form again.</p>';
echo '<input type="button" value="Back" onclick="window.history.back();">';
}
} else { ?>
<!-- Script 2.1 - the form -->
<form action='#' method="post">
<fieldset><legend>Enter your information in the form below:</legend>
<p><label>Name: <input type="text" name="name" size="20" maxlength="40" /></label></p>
<p><label>Email Address: <input type="text" name="email" size="40" maxlength="60" /></label></p>
<p><label for="gender">Gender: </label><input type="radio" name="gender" value="M" /> Male <input type="radio" name="gender" value="F" /> Female</p>
<p><label>Age:
<select name="age">
<option value="0-29">Under 30</option>
<option value="30-60">Between 30 and 60</option>
<option value="60+">Over 60</option>
</select></label></p>
<p><label>Comments: <textarea name="comments" rows="3" cols="40"></textarea></label></p>
</fieldset>
<p align="center"><input type="submit" name="submit" value="Submit My Information" /></p>
</form>
<?php } ?>