PHP Filters are primarily used for validating and sanitizing external input. The PHP filter extension has many predefined filters and flags to validate and sanitize data in various formats.
Many web applications receive external input, like from form submissions. External input is untrustworthy by default. It can be filled with malicious data, or just incorrectly formatted. By using filters, we can sanitize and validate this data, preventing potential security issues and ensuring data integrity.
Validation Filters:
Sanitization Filters:
a) Validating an Email
$email = "john.doe@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "This is a valid email address.";
} else {
echo "This is not a valid email address.";
}
b) Sanitizing a String
$dirtyString = "";
$safeString = filter_var($dirtyString, FILTER_SANITIZE_STRING);
echo $safeString; // Output: alert('Hacked!');
c) Validating an Integer with Options
$number = "10";
$options = array(
"options" => array(
"min_range" => 1,
"max_range" => 20
)
);
if (filter_var($number, FILTER_VALIDATE_INT, $options)) {
echo "The number is within the range.";
} else {
echo "The number is outside the range.";
}
d) Getting and Filtering Input Directly Let's say you have a URL like `example.com?page=5`
$page = filter_input(INPUT_GET, "page", FILTER_VALIDATE_INT);
If the `page` parameter in the URL is an integer, `$page` will have its value. Otherwise, `$page` will be `false`.
Flags are additional settings or instructions you can provide with filters. They modify the behavior of the filters. For instance, `FILTER_FLAG_STRIP_LOW` removes bytes with values less than 32.
$string = "Hello\x00World!";
$clean = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
echo $clean; // Outputs: HelloWorld!
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here