PHP Form Validation – Step-by-Step Guide

What is Form Validation in PHP?

PHP Form Validation is the process of checking user input for accuracy, completeness, and security before storing or processing the data.

✅ Prevents invalid data submission
✅ Protects against security threats like XSS and SQL Injection
✅ Enhances user experience

Create an HTML Form

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    <label for="name">Name:</label>
    <input type="text" name="name">
    
    <label for="email">Email:</label>
    <input type="email" name="email">

    <label for="age">Age:</label>
    <input type="number" name="age">

    <input type="submit" value="Submit">
</form>

Handling Form Data in PHP

Step 1: Initialize Variables

$name = $email = $age = "";
$nameErr = $emailErr = $ageErr = "";

Step 2: Check if the Form is Submitted

 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate Name
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = validateInput($_POST["name"]);
        if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
            $nameErr = "Only letters and spaces allowed";
        }
    }

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

    // Validate Age
    if (empty($_POST["age"])) {
        $ageErr = "Age is required";
    } elseif (!filter_var($_POST["age"], FILTER_VALIDATE_INT)) {
        $ageErr = "Invalid age format";
    } else {
        $age = validateInput($_POST["age"]);
    }
}

Input Validation Function

function validateInput($data) {
    $data = trim($data);       // Remove extra spaces
    $data = stripslashes($data); // Remove backslashes
    $data = htmlspecialchars($data); // Convert special characters
    return $data;
}

Displaying Errors and Data

<p style="color: red;"><?php echo $nameErr; ?></p>
<p style="color: red;"><?php echo $emailErr; ?></p>
<p style="color: red;"><?php echo $ageErr; ?></p>

<h3>Your Input:</h3>
<p>Name: <?php echo $name; ?></p>
<p>Email: <?php echo $email; ?></p>
<p>Age: <?php echo $age; ?></p>

What are the Best Practices for handling Form Validation in php

✅ Use htmlspecialchars() to prevent XSS attacks
✅ Use filter_var() for email and number validation
✅ Implement server-side validation, even if you have client-side JavaScript validation
✅ Prevent CSRF attacks by using tokens
✅ Sanitize data before storing it in the database