Proper validation of form data is very important to guard your form from hackers and spammers.


Example

<!DOCTYPE HTML>  
<html>
    <head>
        <title>Form validation</title>
    </head>
    <body>  

        <?php
        //define variables and set to empty values
        $name = $email = $gender = $comment = $website = "";

        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $name = validate_input($_POST["name"]);
            $email = validate_input($_POST["email"]);
            $website = validate_input($_POST["website"]);
            $comment = validate_input($_POST["comment"]);
            $gender = validate_input($_POST["gender"]);
        }

        function validate_input($data) {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
        }
        ?>

        <h2>PHP Form Validation Example</h2>
        <form method="post" action="">  
            <p>
                Name:<br>
                <input type="text" name="name">
            </p>

            <p>
                E-mail: <br>
                <input type="text" name="email">
            </p>

            <p> 
                Website:<br>
                <input type="text" name="website">
            </p>

            <p>
                Comment:<br>
                <textarea name="comment" rows="5" cols="40"></textarea>
            </p>

            <p>
                Gender:<br>
                <input type="radio" name="gender" value="female">Female
                <input type="radio" name="gender" value="male">Male
                <input type="radio" name="gender" value="other">Other
            </p>
            <p> <input type="submit" name="submit" value="Submit">  </p>
        </form>
    </body>
</html>