Making Sanitary and Validating Form Data

Today, we will cover form validation in PHP. Form validation is very vital to have the input to your structure validated before taking the structure submission records for further processing. When there are many fields in the form, the PHP validation script will become too complex. Furthermore, due to the fact, you are doing a comparable validation for most of the forms that you make, simply too much duplicate effort is spent on structure validations.

The technique of shooting and showing the submitted structure data is pretty simple. In this tutorial, you will learn how to enforce a simple contact form on your website that lets in the consumer send their comment and feedback via email.

We are also going to implement some fundamental security characteristics like sanitization and validation of the user’s input so that consumers can no longer insert potentially dangerous information that compromises the website protection or might break the application.

The following is the all-in-one PHP script which does the following things:

  1. It will ask the users to enter his comments about the website.
  2. The identical script shows the contact structure and procedures of the submitted form data.
  3. The script sanitizes and validates the user inputs. If any required subject (marked with *) is missing or validation failed due to unsuitable inputs the script redisplays the structure with an error message for the corresponding form field.
  4. The script remembers which fields the person has already stuffed in, and prefills those fields when the form redisplayed due to validation error.
  5. If the records submitted through the consumer are desirable and the whole thing goes properly it will ship an email to the internet site administrator and display a success message to the user.

Type the following code in “contact.php” file and shop in your assignment root directory: 

<?php
// Functions to filter user inputs
function filterName($field){
    // Sanitize user name
    $field = filter_var(trim($field), FILTER_SANITIZE_STRING);
    
    // Validate user name
    if(filter_var($field, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
        return $field;
    } else{
        return FALSE;
    }
}    
function filterEmail($field){
    // Sanitize e-mail address
    $field = filter_var(trim($field), FILTER_SANITIZE_EMAIL);
    
    // Validate e-mail address
    if(filter_var($field, FILTER_VALIDATE_EMAIL)){
        return $field;
    } else{
        return FALSE;
    }
}
function filterString($field){
    // Sanitize string
    $field = filter_var(trim($field), FILTER_SANITIZE_STRING);
    if(!empty($field)){
        return $field;
    } else{
        return FALSE;
    }
}
 
// Define variables and initialize with empty values
$nameErr = $emailErr = $messageErr = "";
$name = $email = $subject = $message = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    // Validate user name
    if(empty($_POST["name"])){
        $nameErr = "Please enter your name.";
    } else{
        $name = filterName($_POST["name"]);
        if($name == FALSE){
            $nameErr = "Please enter a valid name.";
        }
    }
    
    // Validate email address
    if(empty($_POST["email"])){
        $emailErr = "Please enter your email address.";     
    } else{
        $email = filterEmail($_POST["email"]);
        if($email == FALSE){
            $emailErr = "Please enter a valid email address.";
        }
    }
    
    // Validate message subject
    if(empty($_POST["subject"])){
        $subject = "";
    } else{
        $subject = filterString($_POST["subject"]);
    }
    
    // Validate user comment
    if(empty($_POST["message"])){
        $messageErr = "Please enter your comment.";     
    } else{
        $message = filterString($_POST["message"]);
        if($message == FALSE){
            $messageErr = "Please enter a valid comment.";
        }
    }
    
    // Check input errors before sending email
    if(empty($nameErr) && empty($emailErr) && empty($messageErr)){
        // Recipient email address
        $to = '[email protected]';
        
        // Create email headers
        $headers = 'From: '. $email . "\r\n" .
        'Reply-To: '. $email . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
        
        // Sending email
        if(mail($to, $subject, $message, $headers)){
            echo '<p class="success">Your message has been sent successfully!</p>';
        } else{
            echo '<p class="error">Unable to send email. Please try again!</p>';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Contact Form</title>
    <style type="text/css">
        .error{ color: red; }
        .success{ color: green; }
    </style>
</head>
<body>
    <h2>Contact Us</h2>
    <p>Please fill in this form and send us.</p>
    <form action="contact.php" method="post">
        <p>
            <label for="inputName">Name:<sup>*</sup></label>
            <input type="text" name="name" id="inputName" value="<?php echo $name; ?>">
            <span class="error"><?php echo $nameErr; ?></span>
        </p>
        <p>
            <label for="inputEmail">Email:<sup>*</sup></label>
            <input type="text" name="email" id="inputEmail" value="<?php echo $email; ?>">
            <span class="error"><?php echo $emailErr; ?></span>
        </p>
        <p>
            <label for="inputSubject">Subject:</label>
            <input type="text" name="subject" id="inputSubject" value="<?php echo $subject; ?>">
        </p>
        <p>
            <label for="inputComment">Message:<sup>*</sup></label>
            <textarea name="message" id="inputComment" rows="5" cols="30"><?php echo $message; ?></textarea>
            <span class="error"><?php echo $messageErr; ?></span>
        </p>
        <input type="submit" value="Send">
        <input type="reset" value="Reset">
    </form>
</body>
</html>

Explanation of code

You might think what that code was all about. OK, let’s get straight into it.

  • The filterNae() function (line no-03) validate input value as a person’s name. A valid name can only contain alphabetical characters (a-z, A-Z).
  • The filterEmail()function (line no-14) validate input value as email address.
  • The filterString() function (line no-25) only sanitize the input value by stripping HTML tags and special characters. It doesn’t validate the input value against anything.
  • The attribute action=”contact.php” (line no-111) inside the <form> the tag specifies that the same contact.php file displays the form as well as processes the form data.
  • The PHP code inside the value attribute of <input> and <textarea> e.g. <?php echo $name; ?> display prefilled value when the form is redisplayed upon validation error.
  • The PHP code inside the .error class e.g. <span class=”error”><?php echo $nameErr; ?></span> display error for the corresponding field.

Validating the Form Contents

When the form is submitted, the following entries will be stored in the $_POST array (or $_GET array depending on the form’s method attribute). The values in the left-hand column are taken from the control’s name attribute, and I’ve also marked whether or not the field is a required field for validation purposes.

If the user does not comply with these rules, an error message will be displayed. Any fields already completed will be left unchanged, allowing the user to simply adjust her input and re-submit the form without having to enter all of the data again. See the example below.

Let’s look at the PHP required for validating the form.

<?php
// define variables and initialize with empty values
$nameErr = $addrErr = $emailErr = $howManyErr = $favFruitErr = "";
$name = $address = $email = $howMany = "";
$favFruit = array();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Missing";
    }
    else {
        $name = $_POST["name"];
    }

    if (empty($_POST["address"])) {
        $addrErr = "Missing";
    }
    else {
        $address = $_POST["address"];
    }

    if (empty($_POST["email"]))  {
        $emailErr = "Missing";
    }
    else {
        $email = $_POST["email"];
    }

    if (!isset($_POST["howMany"])) {
        $howManyErr = "You must select 1 option";
    }
    else {
        $howMany = $_POST["howMany"];
    }

    if (empty($_POST["favFruit"])) {
        $favFruitErr = "You must select 1 or more";
    }
    else {
        $favFruit = $_POST["favFruit"];
    }
}
// the HTML code starts here

The code starts by creating and initializing the variables used in the validation process:

  • A variable for each of the text fields and the favorite fruit array
  • Error message variables for each field

The exception is the brochure checkbox which does not need to be validated as it is an optional field.

Summary

Validation is essential, especially if you are going to store the statistics in a database – bear in mind the old saying, GIGO (Garbage In, Garbage Out), and you won’t go a long way wrong. In this article, you have discovered how to create an easy HTML structure and validate it with PHP. Along the way, a variety of methods have been used to re-display person input and show error messages.

Content Protection by DMCA.com