A form sends strings, even when its controls look like numbers. A visitor can skip the form and send a request directly. PHP filters help you check those values before your application trusts them. The useful question is whether a value satisfies the rule for the job you are doing. An age must be an integer in an allowed range; an email must have an acceptable address format. This reference explains filter_var(), filter_input(), validation filters, and the false return value that often surprises beginners. You will build a quantity validator and learn where filters stop helping.
Validation, sanitization and escaping
Validation answers whether a value is acceptable. FILTER_VALIDATE_INT can accept a number and return an integer, or reject it and return false. Sanitization changes a value, perhaps removing characters. That can help with a deliberate cleanup step, but silently repairing invalid business input is usually a bad idea. A quantity of '2cats' should cause an error rather than become a purchase of two items. Escaping prepares an accepted value for a destination. htmlspecialchars() is for text printed into HTML, while prepared statements keep values separate from SQL. Passing an email filter does not make the string safe for every destination. Keep these steps visible: obtain a scalar value, normalize only what your rules allow, validate it, use it, and escape it when presenting it. That sequence makes errors easier to explain to the person completing the form.
Understand the return value
filter_var() operates on a value you already have. Its first argument is the value, its second selects a filter, and the third supplies options or flags. FILTER_VALIDATE_INT returns an integer on success. FILTER_VALIDATE_BOOLEAN can return a boolean, and FILTER_NULL_ON_FAILURE distinguishes an unrecognized boolean representation from a valid false. Read each filter's return contract rather than assuming every successful result is a string. Zero is a valid integer but false is the failure marker. Test an integer result with === false, not with if (!$result). A loose condition rejects zero and causes bugs in stock counts, ages, offsets, and percentages. A default option can be convenient, but for a submitted form it may conceal bad input. Prefer a visible error when the user provided a value outside your stated rule.
Read request input with shape checks
filter_input(INPUT_GET, 'quantity', FILTER_VALIDATE_INT) reads external input through PHP's filter extension. It does not validate a later modification you made to $_GET; use filter_var() for a transformed value. Missing input and invalid input are separate cases, and flags can change their return values. Another practical approach reads $_GET['quantity'] with a null fallback, requires is_string(), and then calls filter_var(). The shape check matters because quantity[]=2 creates an array instead of a scalar string. Reject unexpected arrays rather than casting them into a misleading value. For an API, decode its JSON and validate those decoded values directly; filter_input() is not a general JSON validator. Keep error messages about the field and rule, without reflecting raw hostile input into HTML.
Choose filters that fit business rules
An integer filter with min_range and max_range can express a quantity from zero through one hundred. These bounds are inclusive. Add a required-field check if an empty value is not permitted. FILTER_VALIDATE_EMAIL checks address syntax; it does not prove the mailbox exists, belongs to the visitor, or can receive mail. Account ownership needs a separate confirmation workflow. FILTER_VALIDATE_URL validates a URL format rather than permission to contact that address. A server making network requests needs a stricter allowed-host policy and protections against contacting internal services. Product prices deserve another decision: floating-point validation identifies a numeric representation, but money calculations often use integer minor units or decimal database columns. Pick the business representation first, then choose validation that supports it.
Mistakes to avoid
Do not apply FILTER_DEFAULT expecting validation. It is effectively raw input, so calling a function named filter does not by itself enforce a rule. Avoid the deprecated FILTER_SANITIZE_STRING; for HTML output use destination-specific escaping. Do not remove characters from a password before checking it, because that changes the person's chosen credential. Trim names only if surrounding spaces have no meaning for your application. Filters do not enforce authorization: a valid order ID still needs an ownership check. An input can be valid while violating a unique constraint because another request saved the same email. Return a helpful field error for expected conflicts and log unexpected failures privately. These distinctions make a form behave consistently under ordinary use and unusual requests.
Plan useful validation cases
Write down examples before connecting a validator to the whole form. For a quantity, include the minimum, maximum, zero, a negative value, whitespace, an empty string, letters after digits, an array, and a missing field. Decide which of those should pass rather than letting conversion rules decide accidentally. If you permit surrounding whitespace, normalize it explicitly and document that choice. If leading zeros matter because a value is an identifier, treat it as a string identifier instead of an integer. Test the same validation routine from the form handler and the API handler so two entry points cannot develop contradictory rules. Validation errors are expected application results, not necessarily exceptional infrastructure failures.
Practice task and worked solution
Build a signup validator with required email and optional age between zero and one hundred twenty. Require scalar strings for submitted fields, then trim their edges only where your rules allow. Reject an empty email before applying FILTER_VALIDATE_EMAIL. For age, distinguish an empty string from a supplied value: empty means not provided, while zero remains a valid age. Apply FILTER_VALIDATE_INT with inclusive range options and compare strictly with false. Store accepted values separately from original field strings so you can repopulate the form without confusing them. The solution returns an array containing errors and accepted data rather than echoing from the validator. Check an invalid email, age zero, and an array-shaped age. Escape old field values in the HTML template.
Continue learning
Review form validation for request handling and PHP security for destination-specific escaping.
See the PHP filter reference for individual return values and options.
PHP Filters and Validation Filters Examples
Each example shows the code, the output it produces and what each part does.
Accept zero and reject malformed quantities
Run this fixed-input example with PHP CLI to inspect the results without a web request.
Expected output is 0: 0, 12: 12, -1: invalid, and 2cats: invalid, on separate lines. Zero survives the strict comparison. The negative input fails the range rule, while the word ending fails the integer rule.
<?php
foreach (['0', '12', '-1', '2cats'] as $raw) {
$quantity = filter_var($raw, FILTER_VALIDATE_INT, [
'options' => ['min_range' => 0, 'max_range' => 100],
]);
echo $raw . ': ' . ($quantity === false ? 'invalid' : $quantity) . PHP_EOL;
}0: 0
12: 12
-1: invalid
2cats: invalidPHP Filters and Validation Filters FAQ
Does filter_var() stop SQL injection?
No. filter_var() checks that a value has the expected shape, such as an integer or an email address, but a perfectly valid value can still contain characters that matter to SQL, such as an apostrophe in a name. Validate business input first, then bind the values in a prepared statement, which is what actually keeps them out of the SQL structure.
Why is zero rejected?
Because a truthiness test treats zero and false alike. filter_var('0', FILTER_VALIDATE_INT) correctly returns 0, but if (!$quantity) reads that 0 as a failure. Compare the result with === false, so only a genuine validation failure is treated as invalid.
Can sanitization fix an email?
Sanitizing removes characters the filter considers invalid, which risks changing the intended address into a different, still valid-looking one, so mail goes to the wrong person. Validate the address instead, and when it fails, ask the visitor for a correction rather than silently altering it.
Does every field need a built-in filter?
No. Built-in filters cover common formats such as integers, floats, emails and URLs. Allowed statuses, product codes and application identifiers often need explicit allowlists, such as in_array($status, ['open', 'closed'], true), or custom checks that express your own business rules.
PHP Filters and Validation Filters Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
A stock field permits zero. Which approach is correct?
PHP Filters and Validation Filters Quiz
2 questions to check what you learned.
Which comparison allows a valid zero?
- !$result
- $result == 0
- $result === false to detect failure
- empty($result)
What does email validation establish?
- Mailbox ownership
- Guaranteed delivery
- SQL safety
- The address matches supported syntax