SakhaliaNetHome PageMilitary HistoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Forms (IV)

PHP Example #67

Validating data in forms

When you use a select menu in a form, you must ensure that the value sent for this element is actually one of the options that are available in the menu. Although the normal user can't send a value that is not listed in the menu, an attacker could build a query that contains any malicious value without using a browser. To simplify the task of showing on screen and validate select menus, the options of the menu are placed in an array. Here we add a select menu to the form built in the previous example.

<?php
$sweets = array('Sesame Seed Puff','Coconut Milk Gelatin Square',
'Brown Sugar Cake','Sweet Rice and Meat');
// Logic to do what is correct based in the hidden parameter _submit_check
if (! array_key_exists('_submit_check', $_POST)) {
$_POST['_submit_check'] = 0;
}
if ($_POST['_submit_check']) {
// If validate_form() returns errors, pass them to show_form()
if ($form_errors = validate_form()) {
show_form($form_errors);
} else {
process_form();
}
} else {
show_form();
}
// Do something when the form is sent
function process_form() {
print "Welcome, " . $_POST['my_name'];
}
// Show the form
function show_form($errors = '') {
// If some errors were passed, print them
if ($errors) {
print 'Please correct these errors: <ul><li>';
print implode('</li><li>', $errors);
print '</li></ul>';
}
print '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
print 'Your name (a string):<br/>';
print '<input type="text" name="my_name"/><br/>';
print 'Your age (an integer number):<br/>';
print '<input type="text" name="my_age"/><br/>';
print 'Your e-mail (a string):<br/>';
print '<input type="text" name="my_email"/><br/>';
print 'Your price (an integer or float number):<br/>';
print '<input type="text" name="my_price"/><br/>';
print 'Date (Year, 4 digits):<br/>';
print '<input type="text" name="year"/><br/>';
print 'Date (Month, 2 digits):<br/>';
print '<input type="text" name="month"/><br/>';
print 'Date(Day, 2 digits):<br/>';
print '<input type="text" name="day"/>'<br/>;
print 'Your order:<br/><select name="order">';
foreach ($GLOBALS['sweets'] as $choice) {
print "<option>$choice</option>\n";
}
print '</select><br/>';
print '<input type="submit" value="Order"/>';
print '<input type="hidden" name="_submit_check" value="1">';
print '</form>';
}
// Verify the input of the form
function validate_form() {
// Start with an empty array of error messages
$errors = array();
// Add an error message if the name is too short
if (strlen($_POST['my_name']) < 3) {
$errors[] = 'Your name must have at least 3 letters long.';
}
// Add an error message if nothing has been typed
if (strlen(trim($_POST['my_name'])) == 0) {
$errors[] = 'You must enter your name.';
}
// Add an error message if the age is not a number or it is out of a certain range
if ($_POST['my_age'] != strval(intval($_POST['my_age']))) {
$errors[] = 'Please enter an integer number for your age.';
} elseif (($_POST['my_age'] < 18) || ($_POST['my_age'] > 65)) {
$errors[] = 'Your age must be at least 18 and no more than 65.';
}
// Add an error message if an e-mail address has not been typed
if (strlen($_POST['my_email']) == 0) {
$errors[] = 'You must enter an e-mail address.';
}
// Add an error message if the e-mail address has
// been typed with incorrect syntax
if (! preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i',
$_POST['my_email'])) {
$errors[] = 'Please enter a valid e-mail address.';
}
// Add an error message if the price is not an integer or a float number
if ($_POST['my_price'] != strval(floatval($_POST['my_price']))) {
$errors[] = 'Please enter a number for the price.';
}
// Obtain the timestamp for 6 months ago
$range_start = strtotime('6 months ago');
// Obtain the timestamp for current time
$range_end = time();
// A four-digit year is in $_POST['year']
// A two-digit month is in $_POST['month']
// A two-digit day is in $_POST['day']
$submitted_date = strtotime($_POST['year'] . '-' .
$_POST['month'] . '-' . $_POST['day']);
if (($range_start > $submitted_date) || ($range_end < $submitted_date)) {
$errors[] = 'Please choose a date less than six months old.';
}
// Add an error message if the option sent is not one of the ones
// contained in the array $sweets[]
if (! in_array($_POST['order'], $GLOBALS['sweets'])) {
$errors[] = 'Please choose a valid order.';
}
// Return the array (possibly empty) of error messages
return $errors;
}
?>
Your name (a string):

Your age (an integer number):

Your e-mail (a string):

Your price (an integer or float number):

Date (Year, 4 digits):

Date (Month, 2 digits):

Date(Day, 2 digits):

Your order: