Source Code Below
<?php
/**************************************************************
Check values entered by user.
The code shown here is meant solely to illustrate the concept
in the main article. There are many different coding methods
that one can use to validate form input.
***************************************************************/
//Initialize array to an empty array
$errMsg = array();
/*
Check to see if the form has been posted. If true, then
check values.
*/
if (isset($_POST['submit'])){
if (trim($_POST['Name']) === ''){
$errMsg[] = 'Please enter your name';
}
//We want to make sure that the phone number is in the format we want
if (!preg_match("/^[0-9]{3}[-]{1,1}[0-9]{4}$/", $_POST['Phone'])){
$errMsg[] = 'Phone number should be entered as digits in the following format: ###-####';
}
/*
If an error has occurred, the array '$errMsg' will have a count greater than zero
so display our error message to the user
*/
if (count($errMsg)!== 0){
foreach ($errMsg as $key => $value){
$tmp .= "<li>$value</li>";
}
echo "An error has occurred:<ul>$tmp</ul>";
} else {
echo "Congratulations! You successfully entered your Name and Phone Number!";
}
}
//Note below that we echoing back to the user the values entered and we are
//making those values browser-safe with the 'htmlentities' function
?>
<form name="myForm" method="POST" action="<?php echo $_SERVER['PHP_SELF']?>">
Name: <input name="Name" type="text" value="<?php echo htmlentities($_POST['Name'])?>">
<br />
Phone: <input name="Phone" type="text" value="<?php echo htmlentities($_POST['Phone'])?>">
<input type="submit" name="submit" value="Submit">
</form>
<hr /> Source Code Below
<hr />
<?php show_source($_SERVER['SCRIPT_FILENAME']); ?>