PHP Tutorial 3 - Form Validation in PHP

Welcome back to the tutorials; this is Tutorial 3, where we will learn to validate a form's data through PHP.

Forms are a crucial part of a web page, without which, no significant input from the user can be expected. Before submitting a form's data to the back-end, it needs to be validated due to certain issues. Form validation through PHP is a process where the form data is posted to the server and the server returns the respective messages related to the validation. Validation of a form's data is generally practiced with the aid of JavaScript because the form's data is validated by the browser only, showing respective messages without returning to the server. Here, we will stick to the form validation process through PHP only.

So the webpage containing the form, index.php, will be like:

<?php include("form.php"); ?>
<html>
    <head>
        <title>PHP Tutorial 3 - Form Validation Demo</title>
    </head>    <body>
        <?php
        /* Form submitted without errors */
        if(isset($_SESSION['submit']))
        {
            if($_SESSION['submit'])
            {
            ?>
                <h1>Form Submitted!</h1>
            <?php
            }
            unset($_SESSION['submit']);
        }
        else // error in the form or first load of the page
        {
        ?>
            <h1>Login</h1>
            <?php
            /* If errors occurred, they will be displayed. */
            if($form->num_errors > 0)
                echo "<font size="2" color="#ff0000">".$form->num_errors." error(s) found</font>";
            ?>
            <form action="process.php" method="POST">
                <table>
                    <tr>
                        <td>Username: </td>
                        <td><input type="text" name="user" maxlength="30" value="<?php echo $form->value("user"); ?>"></td>
                        <td><?php echo $form->error("user"); ?></td>
                    </tr>
                    <tr>
                        <td>Password: </td>
                        <td><input type="password" name="pass" maxlength="30" value="<?php echo $form->value("pass"); ?>"></td>
                        <td><?php echo $form->error("pass"); ?></td>
                    </tr>
                </table>
                <p>
                    <input type="hidden" name="sublogin" value="1">
                    <input type="submit" value="Login">
                </p>
            </form>
        <?php
        }
        ?>
    </body>
</html>

In the above code, under the form section, each field is followed by error messages of the corresponding field. At the first load of the page, all the messages are blank, therefore no message can be seen. But once a form is submitted to the page process.php, the data corresponding to every field is validated and the error messages for the corresponding fields are altered. After the validation of the entire data, the server is again redirected to the page index.php. At this load of the page, the corresponding "new" error messages are visible along with the count of the number of errors.

The contents of process.php goes like this:

 <?php
include("form.php");
class Process
{
    function Process()
    {
        /* User submitted login form */
        if(isset($_POST['sublogin']))
        {
            $this->procLogin();
        }
        else
        {
            header("Location: index.php");
        }
    }    function procLogin()
    {
        global $form;
        /* Username error checking */
        $subuser = $_POST['user'];
        $subpass = $_POST['pass'];
        $field = "user";  //Use field name for username
        if(!$subuser || strlen($subuser = trim($subuser)) == 0)
        {
            $form->setError($field, "* Username not entered");
        }
        $field = "pass";  //Use field name for username
        if(!$subpass || strlen($subpass = trim($subpass)) == 0)
        {
            $form->setError($field, "* Password not entered");
        }
        /* Errors exist, have user correct them */
        if($form->num_errors > 0)
        {
            $_SESSION['value_array'] = $_POST;
            $_SESSION['error_array'] = $form->getErrorArray();
        }
        else
            $_SESSION['submit'] = true; // No errors, form can be submitted now        header("Location: index.php");
    }
};/* Initialize process */
$process = new Process;?>

A file form.php is included in both the pages above. It includes various functions that are called by both the pages. Let us consider the following segment from process.php:

$subuser = $_POST['user'];
$field = "user";  //Use field name for username
if(!$subuser || strlen($subuser = trim($subuser)) == 0)
{$form->setError($field, "* Username not entered");
}
The 'if' condition validates whether the data posted under 'user' field is null or not. If the condition proves to be valid, the error message for the 
'user' field is set to be '*Username not entered'. This is carried out by calling the function '$form->setError($field, "* Username not entered");' from 
the page form.php.Here '$field' contains the name of the field, the data of which is being validated, followed by the message which needs to be set 
for the current field.

The contents of form.php goes like:

<?php
class Form
{
    var $values = array();    //Holds submitted form field values
    var $errors = array();  //Holds submitted form error messages
    var $num_errors;   //The number of errors in submitted form    function Form()
    {
        session_start();
        /**
        * Get form value and error arrays, used when there
        * is an error with a user-submitted form.
        */
        if(isset($_SESSION['value_array']) && isset($_SESSION['error_array']))
        {
            $this->values = $_SESSION['value_array'];
            $this->errors = $_SESSION['error_array'];
            $this->num_errors = count($this->errors);            unset($_SESSION['value_array']);
            unset($_SESSION['error_array']);
        }
        else
        {
            $this->num_errors = 0;
        }
    }    /**
    * setError - Records new form error given the form
    * field name and the error message attached to it.
    */
    function setError($field, $errmsg)
    {
        $this->errors[$field] = $errmsg;
        $this->num_errors = count($this->errors);
    }    /**
    * value - Returns the value attached to the given
    * field, if none exists, the empty string is returned.
    */
    function value($field)
    {
        if(array_key_exists($field,$this->values))
        {
            return htmlspecialchars(stripslashes($this->values[$field]));
        }
        else
        {
            return "";
        }
    }    /**
    * error - Returns the error message attached to the
    * given field, if none exists, the empty string is returned.
    */
    function error($field)
    {
        if(array_key_exists($field,$this->errors))
        {
            return "<font size="2" color="#ff0000">".$this->errors[$field]."</font>";
        }
        else
        {
            return "";
        }
    }    /* getErrorArray - Returns the array of error messages */
    function getErrorArray()
    {
        return $this->errors;
    }
};/* Initialize form */
$form = new Form;?>

A combination of the three pages: index.php, process.php and form.php will help you out in validating a form's data using PHP. 

Keep looking for more articles regarding PHP.

Up Next
    Ebook Download
    View all
    Learn
    View all