All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Form In PHP With Validation

Last Updated : Mar 11, 2024

Form In PHP With Validation

In this article we will show you the solution of form in PHP with validation, in PHP form validation, the script verifies the data in the appropriate fields in accordance with the developer's standards, and if it does not match the requirements, it returns an error.

We will now discuss the idea of how to create form in php with validation with example.

Step By Step Guide On Form In PHP With Validation :-

<!DOCTYPE HTML>
<html>
<head>
   <style>
       .error {color: #FF0000;}
    </style>
</head>
<body>
    <?php
        $nameErr = $emailErr = $genderErr = $websiteErr = "";
        $name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (empty($_POST["name"])) {
            $nameErr = "Please enter a valid name";
        } else {
            $name = test_input($_POST["name"]);
            // check if name only contains letters and whitespace
            if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
            $nameErr = "Only letters and white space allowed";
  }
        }
        if (empty($_POST["email"])) {
            $emailErr = "valid Email address";
        } else {
            $email = test_input($_POST["email"]);
            // check if email address is well-formed
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "The email address is incorrect";
            }
        }
        if (empty($_POST["website"])) {
            $website = "";
        } else {
            $website = test_input($_POST["website"]);
            // check if URL address syntax is valid
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=_|!:,.;]*[-a-z0-9+&@#\/%=_|]/i",$website)) {
            $websiteErr = "Enter a valid Webiste URL";
            }
        }
        if (empty($_POST["comment"])) {
            $comment = "";
  } else {
            $comment = test_input($_POST["comment"]);
        }
        if (empty($_POST["gender"])) {
            $genderErr = "Please select a gender";
        } else {
 $gender = test_input($_POST["gender"]);
        }
        }
        function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
 }
    ?>
    <h2>PHP Form Validation Example</h2>
    <p><span class="error">* required field</span></p>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
        FullName: <input type="text" name="name">
        <span class="error">* <?php echo $nameErr;?></span>
<br><br>
        E-mail address: <input type="text" name="email">
        <span class="error">* <?php echo $emailErr;?></span>
        <br><br>
        Website: <input type="text" name="website">
        <span class="error"><?php echo $websiteErr;?></span>
        <br><br>
Comment: <textarea name="comment" rows="2" cols="10"></textarea>
        <br><br>
        Gender:
        <input type="radio" name="gender" value="female">Female
        <input type="radio" name="gender" value="male">Male
            <span class="error">* <?php echo $genderErr;?></span>
        <br><br>
     <input type="submit" name="submit" value="Submit">
    </form>
    <?php
        echo "<h2> Final Output:</h2>";
        echo $name;
        echo "<br>";
        echo $email;
        echo "<br>";
echo $website;
        echo "<br>";
        echo $comment;
        echo "<br>";
        echo $gender;
    ?>
</body>
</html>
  1. This is a PHP form validation example. Users may enter their name, email address, website, gender, and comment. The form validates the user inputs for name, email, and website before submitting the form.
  2. The code first initializes variables for storing error messages and user input. The variables are empty initially.
  3. Then, using the $_SERVER["REQUEST_METHOD"] variable, the code checks if the form has been submitted. If it has, it proceeds with validating the user input using the test_input() function.
  4. The test_input() function is used to sanitize and validate user input. It removes unnecessary spaces and slashes from the data and changes any special characters into their HTML entities to prevent security vulnerabilities.
  5. The correctness of each input field is then verified. If a field is empty or contains invalid characters or syntax, an error message is stored in the corresponding variable. The user input is saved in the associated variable if the field is legitimate.
  6. Finally, the user input is printed on the page with a header for demonstration purposes. Any errors that occurred would also be shown next to the relevant input area.
  7. The HTML code displays the form and includes the PHP code for validation. It also includes a style tag for the error messages.
  8. In summary, this code is an example of how to validate and sanitize user input in a PHP form.

Conclusion :-

As a result, we have successfully learned how to create form in PHP with validation.

This brings us to the end of the “PHP Form Validation” tutorial. In this demo, you created a registration form for validation with the help of PHP.

I hope this article on form in PHP with validation helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Pragati

Experienced coding content writer who enjoys breaking down complex concepts in programming languages like Java, Python, C, and C++. Over three years of experience producing interesting and relevant content for a variety of entities. Committed to providing concise and easy-to-understand articles that assist readers in easily understanding technology and industry trends in the world of coding and software development.

Follow Pragati On Linkedin 🡪