Broad Network


An HTML Form Validation Project with PHP

PHP Validation of HTML Form Data Made Simple – Part 2

Foreword: In this part of the series I present a project that uses PHP to validate the field values of an HTML Form.

By: Chrysanthus Date Published: 29 Aug 2013

Introduction

This is part 2 of my series, PHP Validation of HTML Form Data - Made Simple. In this part of the series I present a project that uses PHP to validate the field values of an HTML Form. You should have read the previous part of the series before reaching here, as this is a continuation.

Note: in this article, if you cannot see any text or piece of code or if you think something (e.g. an image) is missing or link does not operate, or just want to comment, contact me at forchatrans@yahoo.com .

Project Description
There is an HTML Form in a web page (from localhost) in a browser. The PHP file to do the validation is in a localhost (personal web server) in the home directory. When the PHP file receives the form dataset, it checks if each value of each field has been typed according to the syntax of the data type. If any of the field value is wrongly typed, an error message is sent back to the browser. If all the values are properly typed, a feedback message is sent to the browser indicating so.

The HTML Form
The code for the HTML Form page is:

<!DOCTYPE HTML>
<html>
<head>
    <title>Code Sample</title>
</head>
<body>


    <form method="post" action="http://localhost/valid.php">
        <h3>Supplier Info</h3>
        <p>
            <label>Company Name: <input type="text" name="company" id="company"></label>
        </p>
        <p>
            <label>URL: <input type="text" name="url" id="url"></label>
        </p>
        <p>
            <label>Internet IP: <input type="text" name="ip" id="ip"></label>
        </p>
        <p>
            <label>No. of Workers: <input type="text" name="noW" id="noW"></label>
        </p>
        <p>
            <label>Years in Business: <input type="text" name="years" id="years"></label>
        </p>
        <p>
            Service Company? <label>Yes: <input type="radio" name="cType" value="yes"></label> <label>No: <input type="radio" name="cType" value="no">
        </p>
        <strong>Contact Person</strong><br>
        <p>
            <label>First Name: <input type="text" name="firstname" id="firstname"></label>
        </p>
        <p>
            <label>Last Name: <input type="text" name="lastname" id="lastname"></label>
        </p>
        <p>
            <label>Email: <input type="text" name="email" id="email"></label>
        </p>

        <p>
            <button type="submit">Submit</button>
        </p>

    </form>


</body>
</html>

You should display the page to see what the Form looks like.

The HTTP POST method has been used and the name of the PHP file is, valid.php in the Form action URL of http://localhost/valid.php .

The Data Types Involved
The fields for Company, First name and Last name are of data type text. The field for URL is of data type, URL. The field for Internet IP is of data type IP. The field for Number of Workers is of data type, int. The field for number of Years in Business, is of data type, float. The field for Service Company (is it a service or a product company) is of data type Boolean. The field for Email is of data type, Email.

PHP Validation Technique
The PHP filter_var() function is used to validate all the different data types. With this function, there are certain constants that are used to validate the Boolean, float, int, email, URL, Internet-IP and regexp types. The text type is validated using PHP regular expression. PHP has a data type called the regexp (regular expression) type. You use the regexp type to validate the text type (company, first name, last name, etc) in PHP. For the regexp (text) data type, you still use the filter_var() function but in a special way. Whether you are dealing with the regexp data type or not, the filter_var() function will return the value of the Form field if it is correct by syntax or FALSE if it is wrong by syntax. So for example, an email address properly typed, but to the wrong destination is accepted.

Coding the PHP Script
The first code segment of the PHP script is:

    $company = trim($_POST['company']);
    $url = trim($_POST['url']);
    $ip = trim($_POST['ip']);
    $noW = $_POST['noW'];
    $years = $_POST['years'];
    $cType = $_POST['cType'];
    $firstname = trim($_POST['firstname']);
    $lastname = trim($_POST['lastname']);
    $email = trim($_POST['email']);

The PHP $_POST global variable has been used because the HTTP POST method was used at the web page Form. The received values that had to be trimmed for white spaces in front and after the value, were trimmed.

For the company, firstname and lastname fields, it is assumed that the value consists of just one word, for simplicity. So the regexp used is "/\w*/".

Now, in PHP you can use the = operator in a condition as in:

    if (!($URL = filter_var($url, FILTER_VALIDATE_URL)))

The filter_var() function returns true (correct input) or false. This true or false is assigned to the $URL variable, which still results in true or false (the assigned value). The advantage here is that you have assigned a value (to a variable) in a condition. This variable, declared and assigned in the condition can be used outside the conditional block (if-block).

To test each data type you need a particular constant ID in the filter_var() function. However, testing a regexp needs additional coding.

The code segment to test the Boolean variable is,

    //Test the Service Company radio field for yes or no.
    if (!($CTYPE = filter_var($cType, FILTER_VALIDATE_BOOLEAN)))
        {
            if ($cType != 'no')
                {
                    echo "You have to answer Yes or No for Service Company!";
                }
        }

Here, $cType holds either “yes” or “no” or nothing (empty string - if neither radio buttons was clicked). Now, the filter_var() function returns true if Yes was clicked(selected). If No or nothing was clicked the filter_var() function returns false. If Yes was not clicked, the outer if-block in the code is executed (the outer if-block has no proper statement to itself). If No and Yes were not clicked the inner if-block is executed. So an error message will only be sent back if nothing (neither Yes nor No) is clicked.

If every checking (of field values) goes well, that is all the fields are validated correctly, a feedback is sent to the browser to indicate so. The feedback code is executed in a conditional block (based on the $allFine variable – see below).

Note: with the echo construct, an error message or the feedback message goes to a new page at the browser.

The complete PHP script is:

<?php

    $company = trim($_POST['company']);
    $url = trim($_POST['url']);
    $ip = trim($_POST['ip']);
    $noW = $_POST['noW'];
    $years = $_POST['years'];
    $cType = $_POST['cType'];
    $firstname = trim($_POST['firstname']);
    $lastname = trim($_POST['lastname']);
    $email = trim($_POST['email']);

    $allFine = true;  //This variable indicates that there is no error.

    //test a single word company name
    $optionsC = array();
    $optionsC['options']['regexp'] = "/\w*/";

    if (!($cmpny = filter_var($company, FILTER_VALIDATE_REGEXP, $optionsC)))
        {
            echo "The company name has not been typed correctly!", '<br>';
            $allFine = false;
        }

    //Test the URL
    if (!($URL = filter_var($url, FILTER_VALIDATE_URL)))
        {
            echo "The URL has not been typed correctly!", '<br>';
            $allFine = false;
        }

    //Test the IP
    if (!($IP = filter_var($ip, FILTER_VALIDATE_IP)))
        {
            echo "The IP address has not been typed correctly!", '<br>';
            $allFine = false;
        }

    //Test the integer number of workers
    if (!($NOW = filter_var($noW, FILTER_VALIDATE_INT)))
        {
            echo "Type a whole number for no. of workers!", '<br>';
            $allFine = false;
        }

    //Test the float number of Business years
    if (!($YEARS = filter_var($years, FILTER_VALIDATE_FLOAT)))
        {
            echo "Years in Business e.g. 3 or 3.5 has not been typed correctly!", '<br>';
            $allFine = false;
        }

    //Test the Service Company radio field for yes or no.
    if (!($CTYPE = filter_var($cType, FILTER_VALIDATE_BOOLEAN)))
        {
            if ($cType != 'no')
                {
                    echo "You have to answer Yes or No for Service Company!", '<br>';
                    $allFine = false;
                }
        }

    //test a single word name
    $optionsF = array();
    $optionsF['options']['regexp'] = "/\w*/";

    if (!($fn = filter_var($firstname, FILTER_VALIDATE_REGEXP, $optionsF)))
        {
            echo "The First Name has not been typed correctly!", '<br>';
            $allFine = false;
        }

    //test a single word name
    $optionsL = array();
    $optionsL['options']['regexp'] = "/\w*/";

    if (!($ln = filter_var($lastname, FILTER_VALIDATE_REGEXP, $optionsL)))
        {
            echo "The Last Name has not been typed correctly!", '<br>';
            $allFine = false;
        }

    //test the email
    if (!($EMAIL = filter_var($email, FILTER_VALIDATE_EMAIL)))
        {
            echo "The Email has not been typed correctly!", '<br>';
            $allFine = false;
        }


    //All should be well at this point
    //Send feedback
    if ($allFine == true)
        {
            echo $company, '<br>';
            echo $url, '<br>';
            echo $ip, '<br>';
            echo $noW, '<br>';
            echo $years, '<br>';
            echo $cType, '<br>';
            echo $firstname, '<br>';
            echo $lastname, '<br>';
            echo $email, '<br>';
        }

?>

If all is fine, the feedback data (message) can be sent to an email box or database.

That is it: A project to validate HTML Form data using PHP at the server. It has been made simple, when you compare the version of PHP today with previous versions and other languages.

Chrys

If you like this article, plus it by clicking:

Related Links

Conventional Web Development with PHP and MySQL
PHP Validation of HTML Form Data - Made Simple
Web Live Text Chart Application with PHP and MySQL
Searching a Social Network Site with PHP and MySQL
Page Views with Ajax and PHP and MySQL
More Related Links
Major in Website Design
PHP Course
Web Development Course

BACK

Comments

Become the Writer's Fan
Send the Writer a Message