PHP: Validation of User Data

Derek Bridge

Department of Computer Science,
University College Cork

PHP: Validation of User Data

Aims:

Example form

<form action="process.php" method="get">
    <input type="text" name="firstname" maxlength="30" />
    <input type="text" name="surname" maxlength="30" />   
    <input type="submit" />
</form>

Example PHP script

<?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');
?>

Validation of user's data

Some built-in functions

Checking firstname

Using functions

A function that checks required text fields

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;
}

Rewritten version of the example PHP script from earlier

<?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');
?>

A library for validating user data