PHP Form Validation

Form validation is essential to ensure that the data submitted by users is accurate and secure. PHP provides various methods to validate form data before processing it.

Common Validation Techniques

  • Check if the input fields are empty.
  • Validate the format of the data (e.g., email, URL).
  • Ensure the data meets specific criteria (e.g., minimum length).

Example of PHP Form Validation

<?php
// Initialize variables
$name = $email = $message = "";
$nameErr = $emailErr = $messageErr = "";

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

    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Invalid email format";
    } else {
        $email = $_POST["email"];
    }

    if (empty($_POST["message"])) {
        $messageErr = "Message is required";
    } else {
        $message = $_POST["message"];
    }
}
?>

Explanation: This example demonstrates basic form validation in PHP. It checks if the name, email, and message fields are filled out and validates the email format.

Displaying Validation Errors

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    Name: 
    <?php echo $nameErr; ?>
Email: <?php echo $emailErr; ?>
Message: <?php echo $messageErr; ?>
</form>

Explanation: This code displays the form and shows any validation errors below the respective input fields.