what is filter_var() function in php?

The filter_var() function is used to validate and sanitize form data.

File Name :

The filter_var() function filters a single variable with a specified filter. It takes two parameters:
  • The first is variable you want to check or validate.
  • The type of data check to use such as int, flolat, string etc.

  • File Name :

    $user_name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
    $user_age = filter_var($_POST['age'], FILTER_SANITIZE_INT);
    $mob = mysqli_real_escape_string($sql, filter_var($_POST['phone'], FILTER_VALIDATE_INT));


    The mysqli_real_escape_string() Or real_escape_string() function escapes special characters from a string for use in an SQL query.

    Example :

    File Name :

    <?php
    $name = "<h1>Sana!</h1>";
    $new_name = filter_var($name, FILTER_SANITIZE_STRING);
    echo $new_name;
    ?>

    How to filter an Integer

    <?php
    $age = 36;

    if (!filter_var($age, FILTER_VALIDATE_INT) === false) {
    echo("Age is valid");
    } else {
    echo("Age is not valid");
    }
    ?>

    How to Validate and Sanitize an Email ?

    File Name :

    <?php
    $email_id = "sana@ittutorial.in";

    // Remove all illegal characters from email
    $email = filter_var($email_id , FILTER_SANITIZE_EMAIL);

    // Validate e-mail
    if (!filter_var($email_id , FILTER_VALIDATE_EMAIL) === false) {
    echo("$email_id is a valid email");
    } else {
    echo("$email_id is not a valid email");
    }
    ?>





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here