Introduction
PHP filters help developers check, validate, and sanitize user input before using it in a website. They are useful for checking email addresses, numbers, URLs, and other data. In this chapter, you will practise PHP filter functions and learn how to accept valid input while rejecting incorrect values. PHP Filters and Input Validation Practice Questions with Solutions to help you understand the concepts.
Question 1: Validate an Email Address Using FILTER_VALIDATE_EMAIL
Problem Statement
Create a PHP program that checks whether a student’s email address is valid.
PHP Solution
<?php
$email = "student@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
?>
Sample Output
Valid email address.
Explanation
$emailstores the email address that needs to be checked.filter_var()applies a filter to the given value.FILTER_VALIDATE_EMAILchecks whether the value follows a valid email format.- If validation succeeds, PHP returns the validated value.
- If validation fails, PHP returns
false.
Remember: A valid email format does not guarantee that the email account actually exists.
Concepts Covered
filter_var()FILTER_VALIDATE_EMAIL- Email validation
- Valid and invalid input
Question 2: Validate an Integer Using FILTER_VALIDATE_INT
Problem Statement
Create a PHP program that checks whether a student’s age is a valid integer.
PHP Solution
<?php
$age = "18";
if (filter_var($age, FILTER_VALIDATE_INT) !== false) {
echo "Valid age: " . $age;
} else {
echo "Age must be an integer.";
}
?>
Sample Output
Valid age: 18
Explanation
$agecontains the value to validate.FILTER_VALIDATE_INTchecks whether the value is a valid integer.- The comparison
!== falsechecks validation correctly. - A value such as
"18"is accepted. - A value such as
"18.5"or"eighteen"is rejected.
Important: Use !== false because the integer 0 is also a valid integer, but it evaluates to false in a simple condition.
Concepts Covered
FILTER_VALIDATE_INT- Integer validation
- Strict comparison
- Numeric input checking
Question 3: Validate a Floating-Point Number
Problem Statement
A company wants to accept employee salary values. Create a PHP program that checks whether the entered salary is a valid floating-point number.
PHP Solution
<?php
$salary = "25500.50";
if (filter_var($salary, FILTER_VALIDATE_FLOAT) !== false) {
echo "Valid salary: " . $salary;
} else {
echo "Invalid salary.";
}
?>
Sample Output
Valid salary: 25500.50
Explanation
$salarystores the salary value.FILTER_VALIDATE_FLOATchecks whether the input is a valid floating-point number.!== falseconfirms that validation did not fail.- Decimal values such as
25500.50can be accepted.
Concepts Covered
FILTER_VALIDATE_FLOAT- Decimal number validation
- Salary input checking
Question 4: Validate a Website URL
Problem Statement
Create a PHP program that checks whether a website address is valid.
PHP Solution
<?php
$website = "https://www.example.com";
if (filter_var($website, FILTER_VALIDATE_URL)) {
echo "Valid website URL.";
} else {
echo "Invalid website URL.";
}
?>
Sample Output
Valid website URL.
Explanation
$websitestores the website address.FILTER_VALIDATE_URLchecks whether the value follows a valid URL format.- A URL such as
https://www.example.compasses validation. - An incorrectly formatted address may fail validation.
Concepts Covered
FILTER_VALIDATE_URL- URL validation
- Website address checking
Question 5: Validate an IP Address
Problem Statement
Create a PHP program that checks whether an entered IP address is valid.
PHP Solution
<?php
$ipAddress = "192.168.1.10";
if (filter_var($ipAddress, FILTER_VALIDATE_IP)) {
echo "Valid IP address.";
} else {
echo "Invalid IP address.";
}
?>
Sample Output
Valid IP address.
Explanation
$ipAddressstores the IP address.FILTER_VALIDATE_IPchecks whether the value is a valid IPv4 or IPv6 address.- PHP returns the validated address when it passes.
- Otherwise, it returns
false.
Concepts Covered
FILTER_VALIDATE_IP- IP address validation
- IPv4 and IPv6
Question 6: Validate Only IPv4 Addresses
Problem Statement
Create a PHP program that accepts an IPv4 address and rejects IPv6 addresses.
PHP Solution
<?php
$ipAddress = "192.168.1.10";
if (
filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
) {
echo "Valid IPv4 address.";
} else {
echo "Invalid IPv4 address.";
}
?>
Sample Output
Valid IPv4 address.
Explanation
FILTER_VALIDATE_IPchecks the IP address.FILTER_FLAG_IPV4restricts validation to IPv4 addresses.- An IPv6 address will not pass this validation.
- This is useful when an application specifically requires IPv4 input.
Concepts Covered
FILTER_VALIDATE_IPFILTER_FLAG_IPV4- IPv4 validation
Question 7: Sanitize an Email Address
Problem Statement
Create a PHP program that removes invalid characters from an email address using an email sanitization filter.
PHP Solution
<?php
$email = " student@exa mple.com ";
$cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
echo "Original Email: " . $email;
echo "\nSanitized Email: " . $cleanEmail;
?>
Sample Output
Original Email: student@exa mple.com
Sanitized Email: student@example.com
Explanation
$emailcontains the original email value.FILTER_SANITIZE_EMAILremoves characters that are not permitted by this filter.$cleanEmailstores the sanitized value.- Sanitization changes the input, but it does not prove that the resulting email address is valid.
Remember: Always validate the sanitized email separately when your application requires a valid email address.
Concepts Covered
FILTER_SANITIZE_EMAIL- Email sanitization
- Cleaning user input
Question 8: Sanitize a URL
Problem Statement
Create a PHP program that removes characters not permitted by the URL sanitization filter.
PHP Solution
<?php
$website = "https://www.example.com";
$cleanURL = filter_var($website, FILTER_SANITIZE_URL);
echo "Original URL: " . $website;
echo "\nSanitized URL: " . $cleanURL;
?>
Sample Output
Original URL: https://www.example.com
Sanitized URL: https://www.example.com
Explanation
$websitestores the original URL.FILTER_SANITIZE_URLremoves characters not allowed by the filter.$cleanURLstores the sanitized result.- The original URL remains unchanged because the sanitized result is stored in a separate variable.
Important: Sanitizing a URL does not confirm that it is valid or safe to visit. Use FILTER_VALIDATE_URL when format validation is required.
Concepts Covered
FILTER_SANITIZE_URL- URL sanitization
- Cleaning URL input
Question 9: Validate an Integer Within a Range
Problem Statement
A training institute accepts student ages between 18 and 60. Create a PHP program that validates the entered age and checks whether it falls within this range.
PHP Solution
<?php
$age = "25";
$options = [
"options" => [
"min_range" => 18,
"max_range" => 60
]
];
$validAge = filter_var(
$age,
FILTER_VALIDATE_INT,
$options
);
if ($validAge !== false) {
echo "Age accepted: " . $validAge;
} else {
echo "Age must be between 18 and 60.";
}
?>
Sample Output
Age accepted: 25
Explanation
Here, PHP checks two things:
- Whether the entered value is a valid integer.
- Whether the integer falls between 18 and 60, including both limits.
The options array contains:
min_range: The minimum accepted value.max_range: The maximum accepted value.
For example:
| Input | Result |
|---|---|
| 17 | Rejected |
| 18 | Accepted |
| 25 | Accepted |
| 60 | Accepted |
| 61 | Rejected |
| 25.5 | Rejected |
Concepts Covered
FILTER_VALIDATE_INTmin_rangemax_range- Range validation
Question 10: Create a Student Input Validation System
Problem Statement
Create a PHP program that validates a student’s name, email address, age, and website URL before accepting the student details.
PHP Solution
<?php
$studentName = "Rahul";
$email = "rahul@example.com";
$age = "20";
$website = "https://www.example.com";
$errors = [];
if (trim($studentName) === "") {
$errors[] = "Student name is required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email address.";
}
$options = [
"options" => [
"min_range" => 14,
"max_range" => 60
]
];
$validAge = filter_var(
$age,
FILTER_VALIDATE_INT,
$options
);
if ($validAge === false) {
$errors[] = "Age must be between 14 and 60.";
}
if (!filter_var($website, FILTER_VALIDATE_URL)) {
$errors[] = "Invalid website URL.";
}
if (empty($errors)) {
echo "Student details accepted successfully.";
echo "\nName: " . htmlspecialchars($studentName);
echo "\nEmail: " . htmlspecialchars($email);
echo "\nAge: " . $validAge;
echo "\nWebsite: " . htmlspecialchars($website);
} else {
echo "Please correct the following errors:\n";
foreach ($errors as $error) {
echo "- " . $error . "\n";
}
}
?>
Sample Output
Student details accepted successfully.
Name: Rahul
Email: rahul@example.com
Age: 20
Website: https://www.example.com
Explanation
This program combines several input validation concepts:
- The student’s name is checked to ensure it is not empty.
- The email address is checked using
FILTER_VALIDATE_EMAIL. - The age is checked using
FILTER_VALIDATE_INTwith a minimum and maximum range. - The website is checked using
FILTER_VALIDATE_URL. - Invalid details are stored in the
$errorsarray. - If there are no errors, the student details are displayed.
htmlspecialchars()helps prevent HTML injection when displaying user-controlled text in an HTML page.
Concepts Covered
- Multiple input validation
- Email validation
- Integer range validation
- URL validation
- Error collection
- Safe HTML output
Key Takeaways
filter_var()is used to validate or sanitize individual values.FILTER_VALIDATE_EMAILchecks email format.FILTER_VALIDATE_INTchecks integer values.FILTER_VALIDATE_FLOATchecks decimal numbers.FILTER_VALIDATE_URLchecks URL format.FILTER_VALIDATE_IPchecks IP addresses.FILTER_SANITIZE_EMAILandFILTER_SANITIZE_URLclean input.FILTER_FLAG_IPV4restricts IP validation to IPv4.min_rangeandmax_rangedefine accepted integer limits.- Validation checks whether input meets requirements; sanitization modifies input.
Important: Sanitization is not a replacement for validation. Always validate data according to your application’s requirements. Also, use htmlspecialchars() when displaying untrusted text in HTML, and use prepared statements when working with database queries.
Frequently Asked Questions (FAQs)
1. What are PHP filters?
PHP filters are built-in tools used to validate or sanitize data. They help developers check and clean values received from users.
2. Which function is used for filtering data in PHP?
The filter_var() function is commonly used to validate or sanitize a single variable.
3. What is the difference between validation and sanitization?
Validation checks whether input meets a specific rule. Sanitization modifies input by removing or converting certain characters.
4. How do you validate an email in PHP?
Use filter_var() with FILTER_VALIDATE_EMAIL to check the email format.
5. How do you validate an integer in PHP?
Use FILTER_VALIDATE_INT to check whether a value is a valid integer.
6. How can you validate a number within a specific range?
Use FILTER_VALIDATE_INT with min_range and max_range options to restrict the accepted integer range.
7. What is FILTER_SANITIZE_EMAIL?
It is a PHP filter that removes characters not permitted by the email sanitization filter. The resulting value should still be validated separately.
8. What is FILTER_VALIDATE_URL?
It checks whether a value follows a valid URL format.
9. Can PHP validate IPv4 and IPv6 addresses?
Yes. FILTER_VALIDATE_IP accepts valid IPv4 and IPv6 addresses. You can use FILTER_FLAG_IPV4 or FILTER_FLAG_IPV6 to restrict validation to one type.
10. Is PHP input validation enough to secure a website?
No. Input validation is one part of website security. Applications also need safe output encoding, prepared database statements, access controls, and other protections appropriate to the task.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
