Difference between revisions of "PHP filters"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
Line 1: Line 1:
 
Filters can be used to both sanitize and validate data.  
 
Filters can be used to both sanitize and validate data.  
 +
 +
==Sanitizing a string==
 +
<syntaxhighlight lang=php>
 +
<?php
 +
$str = "<h1>Hello World!</h1>";
 +
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
 +
echo $newstr;
 +
?>
 +
</syntaxhighlight>
  
 
==Validating Integer==
 
==Validating Integer==
Line 15: Line 24:
 
?>  
 
?>  
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
==Validate Email Address==
 +
 +
<syntaxhighlight lang=php>
 +
<?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");
 +
}
 +
?>
 +
</syntaxhighlight>
 +
 +
==Sanitize & Validate URL==
 +
 +
<syntaxhighlight lang=php>
 +
<?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");
 +
}
 +
?>
 +
</syntaxhighlight>
 +
 
Filters available are:
 
Filters available are:
  

Revision as of 09:49, 21 December 2017

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