PHP Filters Advanced

Advanced filtering techniques and multiple input validation

🚀 Advanced PHP Filters

Advanced filters let you validate multiple inputs simultaneously, create custom validation rules, and apply complex filtering options. Master these techniques to build robust, secure applications with efficient data validation.


<?php
// Filter multiple inputs at once
$filters = [
    "email" => FILTER_VALIDATE_EMAIL,
    "age" => FILTER_VALIDATE_INT
];
$result = filter_var_array($_POST, $filters);
print_r($result);
?>
                                    

Advanced Filter Techniques

📦

Multiple Filters

Validate multiple input fields simultaneously using filter_var_array() for efficient batch processing of form data.

<?php
$data = [
    "name" => "John",
    "age" => 25
];
$filters = [
    "name" => FILTER_SANITIZE_STRING,
    "age" => FILTER_VALIDATE_INT
];
$result = filter_var_array($data, $filters);
?>
⚙️

Filter Options

Add custom options like min/max ranges, default values, and flags to fine-tune validation behavior.

<?php
$options = [
    "options" => [
        "min_range" => 1,
        "max_range" => 100,
        "default" => 50
    ]
];
$num = filter_var(75, FILTER_VALIDATE_INT, $options);
?>
🎯

Filter Flags

Use flags to modify filter behavior, such as allowing specific characters or changing validation rules.

<?php
// Allow path in URL
$url = filter_var(
    $input,
    FILTER_VALIDATE_URL,
    FILTER_FLAG_PATH_REQUIRED
);
?>
🔧

Custom Callbacks

Create custom validation functions for complex business logic that built-in filters cannot handle.

<?php
function validateUsername($value) {
    return strlen($value) >= 3;
}
$result = filter_var(
    $username,
    FILTER_CALLBACK,
    ["options" => "validateUsername"]
);
?>

🔹 Filtering Multiple Inputs

Validate an entire array of inputs with filter_var_array():

<?php
// Simulate form data
$_POST = [
    "name" => "John Doe",
    "email" => "[email protected]",
    "age" => "25",
    "website" => "https://example.com"
];

// Define filters for each field
$filters = [
    "name" => FILTER_SANITIZE_STRING,
    "email" => FILTER_VALIDATE_EMAIL,
    "age" => FILTER_VALIDATE_INT,
    "website" => FILTER_VALIDATE_URL
];

// Apply all filters at once
$result = filter_var_array($_POST, $filters);

// Display results
foreach ($result as $key => $value) {
    if ($value === false) {
        echo "$key: Invalid<br>";
    } else {
        echo "$key: $value<br>";
    }
}
?>

Output:

name: John Doe
email: [email protected]
age: 25
website: https://example.com

🔹 Using Filter Options

Add options to customize filter behavior with ranges and defaults:

<?php
$age = 45;

// Validate age with range
$options = [
    "options" => [
        "min_range" => 18,
        "max_range" => 65,
        "default" => 18
    ]
];

$validated_age = filter_var($age, FILTER_VALIDATE_INT, $options);

if ($validated_age !== false) {
    echo "Valid age: $validated_age<br>";
} else {
    echo "Age out of range<br>";
}

// Test with invalid age
$invalid_age = 70;
$result = filter_var($invalid_age, FILTER_VALIDATE_INT, $options);
echo "Result for age 70: " . ($result === false ? "Invalid" : $result);
?>

Output:

Valid age: 45
Result for age 70: Invalid

🔹 Filter Flags

Use flags to modify how filters work:

<?php
// Validate URL with path required
$url1 = "https://example.com/page";
$url2 = "https://example.com";

$result1 = filter_var(
    $url1, 
    FILTER_VALIDATE_URL, 
    FILTER_FLAG_PATH_REQUIRED
);

$result2 = filter_var(
    $url2, 
    FILTER_VALIDATE_URL, 
    FILTER_FLAG_PATH_REQUIRED
);

echo "URL with path: " . ($result1 ? "Valid" : "Invalid") . "<br>";
echo "URL without path: " . ($result2 ? "Valid" : "Invalid") . "<br>";

// Validate IP address (IPv4 only)
$ip = "192.168.1.1";
$valid_ip = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
echo "IP Address: " . ($valid_ip ? "Valid IPv4" : "Invalid");
?>

Output:

URL with path: Valid
URL without path: Invalid
IP Address: Valid IPv4

🔹 Custom Callback Filters

Create your own validation logic using callback functions:

<?php
// Custom validation function
function validatePassword($password) {
    // Password must be at least 8 characters
    if (strlen($password) < 8) {
        return false;
    }
    // Must contain at least one number
    if (!preg_match('/[0-9]/', $password)) {
        return false;
    }
    return $password;
}

// Test passwords
$password1 = "secure123";
$password2 = "weak";

$result1 = filter_var(
    $password1, 
    FILTER_CALLBACK, 
    ["options" => "validatePassword"]
);

$result2 = filter_var(
    $password2, 
    FILTER_CALLBACK, 
    ["options" => "validatePassword"]
);

echo "Password 'secure123': " . ($result1 ? "Valid" : "Invalid") . "<br>";
echo "Password 'weak': " . ($result2 ? "Valid" : "Invalid");
?>

Output:

Password 'secure123': Valid
Password 'weak': Invalid

🔹 Complex Filter Array

Combine filters, options, and flags for comprehensive validation:

<?php
$data = [
    "username" => "john_doe",
    "email" => "[email protected]",
    "age" => "25",
    "website" => "https://example.com/profile"
];

$filters = [
    "username" => [
        "filter" => FILTER_SANITIZE_STRING,
        "flags" => FILTER_FLAG_STRIP_HIGH
    ],
    "email" => [
        "filter" => FILTER_VALIDATE_EMAIL
    ],
    "age" => [
        "filter" => FILTER_VALIDATE_INT,
        "options" => [
            "min_range" => 18,
            "max_range" => 100
        ]
    ],
    "website" => [
        "filter" => FILTER_VALIDATE_URL,
        "flags" => FILTER_FLAG_PATH_REQUIRED
    ]
];

$result = filter_var_array($data, $filters);

foreach ($result as $key => $value) {
    $status = ($value === false || $value === null) ? "❌ Invalid" : "✅ Valid";
    echo "$key: $status<br>";
}
?>

Output:

username: ✅ Valid
email: ✅ Valid
age: ✅ Valid
website: ✅ Valid

🔹 Useful Filter Flags

URL Flags:

  • FILTER_FLAG_PATH_REQUIRED - URL must have a path
  • FILTER_FLAG_QUERY_REQUIRED - URL must have a query string

IP Flags:

  • FILTER_FLAG_IPV4 - Only allow IPv4 addresses
  • FILTER_FLAG_IPV6 - Only allow IPv6 addresses
  • FILTER_FLAG_NO_PRIV_RANGE - Deny private IP ranges

String Flags:

  • FILTER_FLAG_STRIP_LOW - Remove characters with ASCII value < 32
  • FILTER_FLAG_STRIP_HIGH - Remove characters with ASCII value > 127
  • FILTER_FLAG_ENCODE_HIGH - Encode characters with ASCII value > 127

🧠 Test Your Knowledge

Which function filters multiple inputs at once?