PHP filters

From TRCCompSci - AQA Computer Science
Revision as of 08:49, 21 December 2017 by Admin (talk | contribs)
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 are:

  • int
  • boolean
  • float
  • validate_regexp
  • validate_url
  • validate_email
  • validate_ip
  • string
  • stripped
  • encoded
  • special_chars
  • full_special_chars
  • unsafe_raw
  • email
  • url
  • number_int
  • number_float
  • magic_quotes
  • callback