PHP filters

From TRCCompSci - AQA Computer Science
Revision as of 08:53, 21 December 2017 by Admin (talk | contribs) (Filters available)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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 - Validates a boolean
  • FILTER_VALIDATE_EMAIL - Validates an e-mail address
  • FILTER_VALIDATE_FLOAT - Validates a float
  • FILTER_VALIDATE_INT - Validates an integer
  • FILTER_VALIDATE_IP - Validates an IP address
  • FILTER_VALIDATE_REGEXP - Validates a regular expression
  • FILTER_VALIDATE_URL - Validates a URL
  • FILTER_SANITIZE_EMAIL - Removes all illegal characters from an e-mail address
  • FILTER_SANITIZE_ENCODED - Removes/Encodes special characters
  • FILTER_SANITIZE_MAGIC_QUOTES - Apply addslashes()
  • FILTER_SANITIZE_NUMBER_FLOAT - Remove all characters, except digits, +- and optionally .,eE
  • FILTER_SANITIZE_NUMBER_INT - Removes all characters except digits and + -
  • FILTER_SANITIZE_SPECIAL_CHARS - Removes special characters
  • FILTER_SANITIZE_FULL_SPECIAL_CHARS
  • FILTER_SANITIZE_STRING - Removes tags/special characters from a string
  • FILTER_SANITIZE_STRIPPED - Alias of FILTER_SANITIZE_STRING
  • FILTER_SANITIZE_URL - Removes all illegal character from s URL
  • FILTER_UNSAFE_RAW - Do nothing, optionally strip/encode special characters
  • FILTER_CALLBACK - Call a user-defined function to filter data