PHP filters

From TRCCompSci - AQA Computer Science
Revision as of 08:52, 21 December 2017 by Admin (talk | contribs) (Sanitize & Validate URL)
Jump to: navigation, search

Filters can be used to both sanitize and validate data.

Sanitizing a string

<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>

Validating Integer

This code will check if the value is an integer, 10.5 obviously isn't:

<?php
$int = 10.5;

if (filter_var($int, FILTER_VALIDATE_INT)) {
    echo("Integer is valid");
} else {
    echo("Integer is not valid");
}
?>

Validate Email Address

<?php
$email = "john.doe@example.com";

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    echo("$email is a valid email address");
} else {
    echo("$email is not a valid email address");
}
?>

Sanitize & Validate URL

<?php
$url = "https://www.w3schools.com";
 
// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);

// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
    echo("$url is a valid URL");
} else {
    echo("$url is not a valid URL");
}
?>

Filters available

  • FILTER_VALIDATE_BOOLEAN 258 Validates a boolean
  • FILTER_VALIDATE_EMAIL 274 Validates an e-mail address
  • FILTER_VALIDATE_FLOAT 259 Validates a float
  • FILTER_VALIDATE_INT 257 Validates an integer
  • FILTER_VALIDATE_IP 275 Validates an IP address
  • FILTER_VALIDATE_REGEXP 272 Validates a regular expression
  • FILTER_VALIDATE_URL 273 Validates a URL
  • FILTER_SANITIZE_EMAIL 517 Removes all illegal characters from an e-mail address
  • FILTER_SANITIZE_ENCODED 514 Removes/Encodes special characters
  • FILTER_SANITIZE_MAGIC_QUOTES 521 Apply addslashes()
  • FILTER_SANITIZE_NUMBER_FLOAT 520 Remove all characters, except digits, +- and optionally .,eE
  • FILTER_SANITIZE_NUMBER_INT 519 Removes all characters except digits and + -
  • FILTER_SANITIZE_SPECIAL_CHARS 515 Removes special characters
  • FILTER_SANITIZE_FULL_SPECIAL_CHARS
  • FILTER_SANITIZE_STRING 513 Removes tags/special characters from a string
  • FILTER_SANITIZE_STRIPPED 513 Alias of FILTER_SANITIZE_STRING
  • FILTER_SANITIZE_URL 518 Removes all illegal character from s URL
  • FILTER_UNSAFE_RAW 516 Do nothing, optionally strip/encode special characters
  • FILTER_CALLBACK 1024 Call a user-defined function to filter data