HOME HTML EDITOR C JAVA PHP

PHP Form Validation

The primary goal of form validation is security. Hackers often try to send malicious scripts through form fields. Therefore, it is essential to "Sanitize" and "Validate" every piece of data sent by the user.

1. The $_SERVER["PHP_SELF"] Exploit

Often, we use $_SERVER["PHP_SELF"] in the form's action attribute so that the form submits to the same page. However, if this is not sanitized, a hacker can inject scripts through the URL (known as a Cross-Site Scripting or XSS Attack).

<!-- Safe way to use PHP_SELF -->
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

2. Data Sanitization Function

Instead of writing the same cleaning code for every field, it is better to create a reusable function to clean the data:

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

3. How it Works in Practice

When the form is submitted, we pass every input variable through our test_input() function:

<?php
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = test_input($_POST["name"]);
    $email = test_input($_POST["email"]);
    $gender = test_input($_POST["gender"]);
  }
?>

4. Validation Checklist

During validation, we typically check for these three things:

Security Tip: Always use htmlspecialchars(). This function converts tags like <script> into &lt;script&gt;, ensuring the browser treats it as plain text instead of executing it.