PHP Filters: Robust Input Validation & Data Sanitization

One of the most important rules in web security is: "Never trust user input." Malicious or poorly formatted user inputs can break database queries, cause server crashes, or trigger Cross-Site Scripting (XSS) vulnerabilities. PHP provides a powerful built-in Filter Extension centered around the filter_var() and filter_input() functions designed specifically to validate and sanitize external data.

Validation vs Sanitization: Understanding the Distinction

  • Sanitize Filters: Modify the input by stripping or encoding dangerous characters (e.g. removing HTML tags). Returns the cleansed string.
  • Validate Filters: Strictly test whether the input matches a valid specification (e.g. valid IP address, valid URL, valid integer). Returns the value on success or false on failure.

1. Validating and Sanitizing Email Addresses

<?php
    $emailInput = "  vikram.aditya+test@veewom.com  ";

    // Step 1: Sanitize by removing illegal characters & trimming
    $cleanEmail = filter_var(trim($emailInput), FILTER_SANITIZE_EMAIL);

    // Step 2: Validate against RFC email standards
    if (filter_var($cleanEmail, FILTER_VALIDATE_EMAIL)) {
        echo "Valid Email: " . $cleanEmail . "<br>";
    } else {
        echo "Invalid Email Address provided!<br>";
    }
?>

2. Validating Integers within a Range (e.g. Student Age)

<?php
    $studentAge = "21"; // String from form submission

    // Validate integer between 18 and 30
    $options = [
        "options" => [
            "min_range" => 18,
            "max_range" => 30
        ]
    ];

    if (filter_var($studentAge, FILTER_VALIDATE_INT, $options) !== false) {
        echo "Valid candidate age: $studentAge years.<br>";
    } else {
        echo "Eligibility Error: Candidate must be between 18 and 30 years.<br>";
    }
?>

3. Validating URLs and IP Addresses (IPv4 & IPv6)

<?php
    $website = "https://veewom.com";
    if (filter_var($website, FILTER_VALIDATE_URL)) {
        echo "Valid Web Address.<br>";
    }

    $clientIP = "192.168.1.1";
    if (filter_var($clientIP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        echo "Valid IPv4 Network Address.";
    }
?>

Essential PHP Filters Reference Table

Filter Constant Type Validation / Sanitization Purpose
FILTER_VALIDATE_EMAILValidateValidates standard RFC email address format.
FILTER_VALIDATE_INTValidateChecks if value is a valid integer.
FILTER_VALIDATE_FLOATValidateChecks if value is a floating point number.
FILTER_VALIDATE_URLValidateValidates standard HTTP/HTTPS URL address.
FILTER_VALIDATE_IPValidateValidates IPv4 or IPv6 network addresses.
FILTER_SANITIZE_EMAILSanitizeRemoves all characters except letters, digits, and special email symbols.
FILTER_SANITIZE_URLSanitizeRemoves all illegal URL characters.

BCA / CS University Exam Corner

High-Frequency Exam Question:

Q: Why must you check filter_var($val, FILTER_VALIDATE_INT) !== false with strict comparison?
A: If the integer being tested is 0, loose comparison if (filter_var(0, FILTER_VALIDATE_INT)) evaluates 0 to false! Strict comparison (!== false) guarantees that valid integers of value 0 are recognized correctly.

Interactive Student Practice Session

Exercise 30.1: Write a script that validates user input for a website URL, rejecting it if it lacks an "https://" scheme.

Exercise 30.2: Write a function that accepts an array of raw form strings and sanitizes all of them using filter_var_array().

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!