GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • <form>
  • <input>
  • <textarea>

This view

  • Original page
  • New address

GeezerVison is showing www.tutorialrepublic.com — PHP Form Validation - Tutorial Republic

TutorialRepublic
HOME HTML5 CSS3 JAVASCRIPT JQUERY BOOTSTRAP5 v4.6 PHP7 SQL REFERENCES EXAMPLES FAQ SNIPPETS Online HTML Editor
PHP BASIC
PHP Introduction PHP Getting Started PHP Syntax PHP Variables PHP Constants PHP Echo and Print PHP Data Types PHP Strings PHP Operators PHP If…Else PHP Switch…Case PHP Arrays PHP Sorting Arrays PHP Loops PHP Functions PHP Math Operations PHP GET and POST
PHP ADVANCED
PHP Date and Time PHP Include Files PHP File system PHP Parsing Directories PHP File Upload PHP File Download PHP Cookies PHP Sessions PHP Send Email PHP Form Handling PHP Form Validation PHP Filters PHP Error Handling PHP Classes and Objects PHP Magic Constants PHP JSON Parsing PHP Regular Expressions PHP Exception Handling
PHP & MySQL DATABASE
PHP MySQL Introduction PHP MySQL Connect PHP MySQL Create Database PHP MySQL Create Table PHP MySQL Insert PHP MySQL Prepared PHP MySQL Last Inserted ID PHP MySQL Select PHP MySQL Where PHP MySQL Limit PHP MySQL Order By PHP MySQL Update PHP MySQL Delete PHP MySQL CRUD Application PHP MySQL Ajax Search PHP MySQL Login System
PHP EXAMPLES
PHP Practice Examples PHP FAQ's Answers
PHP REFERENCE
PHP String Functions PHP Array Functions PHP File System Functions PHP Date/Time Functions PHP Calendar Functions PHP MySQLi Functions PHP Filters PHP Error Levels More references
Advertisements

PHP Form Validation

In this tutorial you'll learn how to sanitize and validate form data using PHP filters.

Sanitizing and Validating Form Data

As you have seen in the previous tutorial, the process of capturing and displaying the submitted form data is quite simple. In this tutorial you will learn how to implement a simple contact form on your website that allows the user to send their comment and feedback through email. We will use the same PHP mail() function to send the emails.

We are also going to implement some basic security feature like sanitization and validation of the user's input so that user can not insert potentially harmful data that compromise the website security or might break the application.

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

  • It will ask the users to enter his comments about the website.
  • The same script displays the contact form and process the submitted form data.
  • The script sanitizes and validates the user inputs. If any required field (marked with *) is missing or validation failed due to incorrect inputs the script redisplays the form with an error message for corresponding form field.
  • The script remembers which fields the user has already filled in, and prefills those fields when the form redisplayed due to validation error.
  • If the data submitted by the user are acceptable and everything goes well it will send an email to the website administrator and display a success message to the user.

Type the following code in "contact.php" file and save in your project root directory:

Example

Download
<?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 filterName() function (line no-03) validate input value as 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> tag specifies that the same contact.php file display the form as well as process the form data.
  • The PHP code inside the value attribute of <input> and <textarea> e.g. <?php echo $name; ?> display prefilled value when 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 corresponding field.

Rest the thing we have already covered in previous chapters. To learn more about sanitize and validate filters, please check out the PHP Filter reference.

Note: You need to setup a mail server on your machine for the PHP mail() function to work. If you just want to implement the form validation you can replace the mail part (line no. 81 to 94) with your own custom code.

Previous Page Next Page
Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties
Advertisements

Is this website helpful to you? Please give us a like, or share your feedback to help us improve. Connect with us on Facebook and Twitter for the latest updates.

About Us

Our Story Terms of Use Privacy Policy

Contact

Contact Us Report Error Guest Posts Advertise

Interactive Tools

Bootstrap Icon Search Utility HTML Formatter Title & Meta Length Calculator HTML Color Picker Bootstrap Button Generator SQL Playground Font Awesome Icon Finder HTML Editor

TutorialRepublic

BMC
Copyright © 2026 Tutorial Republic. All Rights Reserved.
Share This:
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.