PHP Sanitize Filters Example

To sanitize data using php filter extension we need to use the PHP's filter_var() function. The basic syntax of the function is :
 filter_var(variable, filter, options)
Where the first parameter variable is the value to be filtered, the second parameter filter is the sanitize filter ID to be applied, and the third parameter is the array of options related to filter. The last two parameters are optional. Now lets see some example of it.

Sanitize Email Address :
<?php

  $email = "<>johnsnow@example.com</>";
  $email = filter_var($email, FILTER_SANITIZE_EMAIL);
  echo $email;

?>
Output :


johnsnow@example.com

Sanitize a String :
<?php

  $str = "<b>Hello world. This is the TEST String.</b>";
  $str = filter_var($str, FILTER_SANITIZE_STRING);
  echo $str;

?>
Output :

Hello world. This is the TEST String.

Sanitize URL
<?php

  $url = "http://www.mycsnotes.com";
  $url = filter_var($url, FILTER_SANITIZE_URL);
  echo $url;

?>
Output :

http://www.mycsnotes.com

Sanitize integer value :
<?php

  $int = 12.20;
  $int = filter_var($int, FILTER_SANITIZE_NUMBER_INT);
  echo $int . "<br/>";

  $int = -80.2;
  $int = filter_var($int, FILTER_SANITIZE_NUMBER_INT);
  echo $int . "<br/>";

  $int = 90.2;
  $int = filter_var($int, FILTER_SANITIZE_NUMBER_INT);
  echo $int;

?>
Output :

122
-802
902


Next Topic :