HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Form Validation

Data security is the most critical part of form handling. You should never trust user input. Hackers can use forms to inject malicious scripts (XSS) or database commands. Validation ensures your data is clean, correct, and safe.


1. The Sanitization Logic

To keep your code organized, create a function that cleans every piece of input before you use it.

<?php
    function test_input($data) {
        $data = trim($data);            // Removes extra spaces/newlines
        $data = stripslashes($data);    // Removes backslashes
        $data = htmlspecialchars($data);// Converts special chars to HTML entities
        return $data;
    }
?>

2. Required Fields

You can check if a field is empty before processing. If it is, display an error message to the user.

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

3. Validating Specific Data

PHP provides filter_var() for advanced validation like emails and URLs.

Validate Email

<?php
    $email = test_input($_POST["email"]);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $emailErr = "Invalid email format";
    }
?>

Validate URL

<?php
    $website = test_input($_POST["website"]);
    if (!filter_var($website, FILTER_VALIDATE_URL)) {
        $websiteErr = "Invalid URL";
    }
?>
Why htmlspecialchars()? It converts characters like < and > into &lt; and &gt;. This prevents browsers from executing a script tag if a user tries to inject one.
Important: Client-side validation (using HTML5 required) is great for UX, but server-side validation in PHP is mandatory for security.

Key Takeaways

  • Always use htmlspecialchars() to prevent XSS attacks.
  • Use trim() and stripslashes() to clean up unnecessary characters.
  • The empty() function checks for required data.
  • Use filter_var() for structured data like Email and URLs.
  • Validation happens before you save data to a database.