Aims:
<form action="process.php" method="get">
<input type="text" name="firstname" maxlength="30" />
<input type="text" name="surname" maxlength="30" />
<input type="submit" />
</form>
<?php
require_once('output_functions.php');
output_header('Now I know all about you', 'stylesheet.css');
$firstname = $_GET['firstname'];
$surname = $_GET['surname'];
output_paragraph("Hello {$firstname} {$surname}");
output_footer('University College Cork');
?>
maxlength="30",
we must explicitly check for this too. Why?
isset($v): returns true if
$v is non-null; false otherwise
trim($s): strips leading and trailing spaces from string
$s, e.g. trim(' Hugh ') returns
'Hugh'
strlen($s): returns the number of chars in string
$s, e.g. strlen('abc') returns 3
is_null,
empty,
is_int/
is_integer/
is_long,
is_float/
is_double/
is_real,
is_numeric
firstname out of the URL:
$error = '';
if ( ! isset($_GET['firstname']) )
{
$error = "Firstname is required";
}
firstname, we need to check surname
in a similar way
$errors
array
validation_functions.php
function get_required_string( &$user_data, $name, $label, $maxlength, &$errors )
{
if ( ! isset($user_data[$name]) )
{
$errors[$name] = "{$label} is required";
return NULL;
}
$value = trim($user_data[$name]);
if ( $value == '' )
{
$errors[$name] = "{$label} is required";
return NULL;
}
if ( strlen($value) > $maxlength )
{
$errors[$name] = "{$label} must be {$maxlength} characters or less";
return NULL;
}
return $value;
}
<?php
require_once('output_functions.php');
require_once('validation_functions.php');
output_header('Now I know all about you', 'stylesheet.css');
$errors = array();
$firstname = get_required_string( $_GET, 'firstname', 'Firstname', 30, $errors );
$surname = get_required_string( $_GET, 'surname', 'Surname', 30, $errors );
if ( count($errors) > 0 )
{
output_paragraph('You have errors!');
output_unordered_list(array_values($errors));
}
else
{
output_paragraph("Hello {$firstname} {$surname}");
}
output_footer('University College Cork');
?>
$errors = array();
$age = get_required_int( $_GET, 'age', 'Age', 3, $errors, 0, 120 );
$weight_in_kg = get_required_float( $_GET, 'weight', 'Weight', $errors, 0, 500 );
if ( count( $errors ) > 0 )
{
}
else
{
}