PHP: A simple form with validation

This entry is part 41 of 54 in the series PHP Tutorial

This is a form with a simple validation function.

The validate_form( ) function returns false if $_POST[‘my_name’] is less than three characters long, and returns true otherwise.

<?php

// Logic to do the right thing based on
// the hidden _submit_check parameter
if (array_key_exists('submit_check', $_POST)) {
    if (validate_form( )) {
        process_form( );
    } else {
        show_form( );
        echo 'Name must be at least 3 characters long';
    }
} else {
    show_form( );
}

// Do something when the form is submitted
function process_form( ) {
    print 'Hello, '. $_POST['my_name'];
}

// Display the form
function show_form( ) {
    print<<< html_output
<form method='POST' action='$_SERVER[PHP_SELF]'>
Your name: <input type='text' name='my_name'>
<br/>
<input type='submit' value='Say Hello'>
<input type='hidden' name='submit_check' value='1'>
</form>
html_output;
}

// Check the form data
function validate_form( ) {
    // Is my_name at least 3 characters long?
    if (strlen($_POST['my_name']) < 3) {
        return false;
    } else {
        return true;
    }
}

?>

Series Navigation<< PHP: Using hidden parameters to test for form submission
PHP: Form with a separate php script file >>