Course Content
About Lesson

PHP Form Validation

Forms allow users to give input, but:

  • A user might enter the wrong data, for example, typing a name in the email field.
  • A user might leave required fields blank.
  • A malicious user might try to hack the system, such as through XSS or SQL injection.

That’s why validation means checking the data and making it safe.

  1. Validation: Check if the data is correct, including format, type, and required fields.
  2. Sanitization: Clean the data by removing spaces, slashes, HTML tags, and other unwanted characters.
PHP
if (empty($_POST["name"])) {
    echo "Name is required";
}
PHP
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format";
}
PHP
if (!is_numeric($age)) {
    echo "Age must be a number";
}
PHP
if (strlen($password) < 6) {
    echo "Password must be at least 6 characters";
}
PHP
function clean_input($data) {
    $data = trim($data);              // remove spaces
    $data = stripslashes($data);      // remove slashes
    $data = htmlspecialchars($data);  // convert <script> into safe text
    return $data;
}
HTML
<!-- FORM.HTML-->
<form method="post" action="validate.php">
  Name: <input type="text" name="name"><br><br>
  Email: <input type="text" name="email"><br><br>
  Age: <input type="text" name="age"><br><br>
  Password: <input type="password" name="password"><br><br>
  <input type="submit" value="Submit">
</form>
PHP
//VALIDATE.PHP
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Sanitize function
    function clean_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }

    // Name Validation
    if (empty($_POST["name"])) {
        echo "❌ Name is required.<br>";
    } else {
        $name = clean_input($_POST["name"]);
        echo "✅ Name: $name <br>";
    }

    // Email Validation
    if (empty($_POST["email"])) {
        echo "❌ Email is required.<br>";
    } elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
        echo "❌ Invalid email format.<br>";
    } else {
        $email = clean_input($_POST["email"]);
        echo "✅ Email: $email <br>";
    }

    // Age Validation
    if (empty($_POST["age"])) {
        echo "❌ Age is required.<br>";
    } elseif (!is_numeric($_POST["age"])) {
        echo "❌ Age must be a number.<br>";
    } elseif ($_POST["age"] < 18) {
        echo "❌ You must be at least 18 years old.<br>";
    } else {
        $age = clean_input($_POST["age"]);
        echo "✅ Age: $age <br>";
    }

    // Password Validation
    if (empty($_POST["password"])) {
        echo "❌ Password is required.<br>";
    } elseif (strlen($_POST["password"]) < 6) {
        echo "❌ Password must be at least 6 characters long.<br>";
    } else {
        $password = clean_input($_POST["password"]);
        echo "✅ Password looks good.<br>";
    }
}
?>