filter_has_var() function in PHP

The filter_has_var() function is used to check whether a variable of a specified input type exists or not. This is particularly useful for validating user input from forms, URLs, and other sources.

Syntax

filter_has_var(type, var)

Parameters

  • type − Specifies the input type to check. Available options are:

    • INPUT_GET − GET variables
    • INPUT_POST − POST variables
    • INPUT_COOKIE − COOKIE variables
    • INPUT_SERVER − SERVER variables
    • INPUT_ENV − Environment variables
  • var − The name of the variable to check for existence

Return Value

Returns true if the variable exists, false otherwise.

Example 1: Checking GET Variables

This example demonstrates checking for a GET parameter in the URL −

<?php
    if (!filter_has_var(INPUT_GET, "email")) {
        echo "Email parameter isn't there!";
    } else {
        echo "Email parameter is there!";
    }
?>

If accessed without ?email=something in the URL:

Email parameter isn't there!

Example 2: Checking POST Variables

Checking if a form field was submitted via POST −

<?php
    if (filter_has_var(INPUT_POST, "username")) {
        echo "Username field was submitted";
    } else {
        echo "Username field is missing";
    }
?>

Example 3: Checking Server Variables

You can also check for server environment variables −

<?php
    if (filter_has_var(INPUT_SERVER, "HTTP_USER_AGENT")) {
        echo "User agent information is available";
    } else {
        echo "User agent information not found";
    }
?>

Conclusion

The filter_has_var() function provides a safe way to check for the existence of input variables before processing them. Always validate input existence before attempting to use the values to avoid undefined variable errors.

Updated on: 2026-03-15T07:32:10+05:30

444 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements