PHP Complete Form Example

Welcome to The Coding College, your ultimate destination to learn coding concepts! In this tutorial, we’ll create a complete PHP form example from scratch. This form will include fields like name, email, website, and comments, along with validation and sanitization using PHP.

What is a Complete Form?

A complete form handles user input, validates the data, and sanitizes it before processing. This ensures data accuracy, integrity, and security. In this example, the form includes:

  • Text Input (Name and Website)
  • E-mail Input (E-mail validation)
  • Text Area (Comments)
  • Radio Buttons (Gender selection)

Features:

  1. Client-side and server-side validation.
  2. Input sanitization using PHP.
  3. Error feedback for each field.
  4. Displaying submitted data upon successful validation.

HTML and PHP: The Complete Form Example

The HTML Form

Below is the HTML structure of the form:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>PHP Complete Form Example</title>
    <style>
        .error { color: red; }
    </style>
</head>
<body>
    <h2>PHP Form Example</h2>
    <p><span class="error">* Required field</span></p>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        Name: <input type="text" name="name">
        <span class="error">* <?php echo $nameErr ?? ''; ?></span>
        <br><br>

        E-mail: <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="5" cols="40"></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>

        <button type="submit">Submit</button>
    </form>
</body>
</html>

PHP Script for Handling Form Data

Here’s the PHP script to validate, sanitize, and process the form:

<?php
// Initialize variables and error messages
$name = $email = $website = $comment = $gender = "";
$nameErr = $emailErr = $websiteErr = $genderErr = "";

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Validate Name
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } 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";
        }
    }

    // Validate E-mail
    if (empty($_POST["email"])) {
        $emailErr = "E-mail is required";
    } else {
        $email = test_input($_POST["email"]);
        // Check if email address is valid
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
        }
    }

    // Validate Website
    if (!empty($_POST["website"])) {
        $website = test_input($_POST["website"]);
        // Check if URL is valid
        if (!filter_var($website, FILTER_VALIDATE_URL)) {
            $websiteErr = "Invalid URL";
        }
    }

    // Sanitize Comment
    if (!empty($_POST["comment"])) {
        $comment = test_input($_POST["comment"]);
    }

    // Validate Gender
    if (empty($_POST["gender"])) {
        $genderErr = "Gender is required";
    } else {
        $gender = test_input($_POST["gender"]);
    }

    // If no errors, display the submitted data
    if (empty($nameErr) && empty($emailErr) && empty($websiteErr) && empty($genderErr)) {
        echo "<h3>Form Submitted Successfully!</h3>";
        echo "<strong>Name:</strong> $name <br>";
        echo "<strong>Email:</strong> $email <br>";
        echo "<strong>Website:</strong> $website <br>";
        echo "<strong>Comment:</strong> $comment <br>";
        echo "<strong>Gender:</strong> $gender <br>";
    }
}

// Function to sanitize input
function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

How It Works

  1. Form Submission:
    • The form is submitted using the POST method, and $_SERVER["PHP_SELF"] directs the data back to the same script for processing.
  2. Input Validation:
    • Name: Ensures only letters and whitespace are allowed.
    • E-mail: Checks for a valid email format using FILTER_VALIDATE_EMAIL.
    • Website: Ensures the URL is correctly formatted.
    • Gender: Requires a value to be selected.
  3. Input Sanitization:
    • All inputs are passed through the test_input() function to remove harmful or unnecessary characters.
  4. Error Feedback:
    • Error messages are displayed beside the respective fields for incomplete or invalid input.
  5. Data Display:
    • If all fields are valid, the sanitized input data is displayed.

Example Output

Case 1: Successful Form Submission

When valid data is submitted:

Form Submitted Successfully!
Name: John Doe
Email: [email protected]
Website: https://www.johndoe.com
Comment: This is a test comment.
Gender: Male

Case 2: Validation Errors

If the form is submitted with invalid or incomplete data, errors are displayed:

Name is required
E-mail is required
Gender is required

Best Practices for Handling PHP Forms

  1. Use htmlspecialchars():
    • Prevents XSS (Cross-Site Scripting) attacks by escaping special characters.
  2. Use filter_var():
    • For validating inputs like emails and URLs.
  3. Combine Client-Side and Server-Side Validation:
    • Use JavaScript for instant feedback but always validate on the server.
  4. Secure Data Handling:
    • Never trust user inputs; always sanitize and validate.

Enhancements You Can Add

  • Dropdown Menus: Use <select> elements for additional options.
  • Password Fields: Add input type password for secure login forms.
  • File Uploads: Enable users to upload files with proper security checks.
  • Session Management: Use sessions to store data temporarily between form submissions.

Conclusion

Creating a complete form in PHP involves careful validation and sanitization to ensure data accuracy and security. This tutorial demonstrated how to build a fully functional form with essential fields, error handling, and data processing.

For more programming tutorials and resources, visit The Coding College. Start building amazing forms today! 🚀

Leave a Comment