PHP : Validating and Sanitizing User Input Data with Filters

Sanitizing data means removing any illegal character from the data. sanitizing user input is one of the most common tasks in a web application.
To make this task easier PHP provides native filter extension that you can use to sanitize the data such as e-mail addresses, URLs, IP addresses, etc.
To validate data using filter extension you need to use the PHP's filter_var() function. The basic syntax of this function can be given with:

filter_var(variable, filter, options)

This function takes three parameters out of which the last two are optional. The first parameter is the value to be filtered, the second parameter is the ID of the filter to apply, and the third parameter is the array of options related to filter. Let's see how it works.

Sanitizing a String

Following example will sanitize a string by removing all HTML tags from it-

<?php
// Sample user comment
$comment = "<h1>Sanitizing and validating examples</h1>";
 
// Sanitize and print comment string
$sanitizedExp = filter_var($comment, FILTER_SANITIZE_STRING);
echo $sanitizedComment;
?>

Output

Sanitizing and validating examples

Validate Integer Values

<?php
// Sample user comment
$int = 20;
 
if(filter_var($int, FILTER_VALIDATE_INT)){
    echo "The <b>$int</b> is a valid integer";
} else{
    echo "The <b>$int</b> is not a valid integer";
}

?>


Validate Email Address

<?php
$email = "waliullahmca786@gmail.co<m>";
// Remove all illegal characters
// from email
$nemail = filter_var($email, FILTER_SANITIZE_EMAIL);
echo $nemail;
?>

Validate IP Addresses

<?php
$ipAddress= "172.16.254.1<m>";
// Remove all illegal characters
// from email
$ipAddressfilter_var($ipAddressFILTER_VALIDATE_IP);
echo $ipAddress;
?>




No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...