Filtering in PHP is super easy with the built in filter_var
() function. Filtering is essential when taking in form input or applying logic to any set of data. This is especially crucial when sanitizing user input in order to prevent XSS and Sql injection attacks.
filter_var ( mixed$variable [, int $filter = FILTER_DEFAULT [, mixed$options ]] ) : mixed
Grab the code below to see how these functions work and head over to php.net and w3Schools for more information.
<?php
print "\n\n";
$int = 311;
$min = 1;
$max = 499;
if (filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max))) === false) {
print("Variable value is not within the legal range\n");
} else {
print("Variable value is within the legal range\n");
}
$int = 511;
if (filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max))) === false) {
print("Variable value is not within the legal range\n");
} else {
print("Variable value is within the legal range\n");
}
print "\n\n";
$ip = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
print("$ip is a valid IPv6 address\n");
} else {
print"$ip is not a valid IPv6 address\n";
}
$ip = "192.168.2.1";
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) {
print("$ip is a valid IPv6 address\n");
} else {
print"$ip is not a valid IPv6 address\n";
}
print "\n\n";
$url = "https://www.gunnard.org?q=b";
if (!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED) === false) {
print("$url is a valid URL with a query string\n");
} else {
print("$url is not a valid URL with a query string\n");
}
$url = "https://www.gunnard.org?q=b";
if (!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED) === false) {
print("$url is a valid URL with a query string\n");
} else {
print("$url is not a valid URL with a query string\n");
}
$url = "https://www.gunnard.org";
if (!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED) === false) {
print("$url is a valid URL with a query string\n");
} else {
print("$url is not a valid URL with a query string\n");
}
print "\n\n";
$str = "<h1>Hello WorldÆØÅ!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
print $str ."<-- is what the string used to be before sanitization\n";
print $newstr;
Be First to Comment