Summary: in this tutorial, you’ll learn about the filter_has_var()
function and how to use it to check if a variable exists in an input.
Introduction to the filter_has_var() function #
The filter_has_var()
function checks if a variable of a specific input type exists. The filter_has_var()
function is a part of PHP’s filter extension.
Here’s the syntax of the filter_has_var()
function:
filter_has_var ( int $input_type , string $var_name ) : bool
Code language: PHP (php)
The function has the two parameters:
$input_type
is the type of input that you want to check for a variable. The valid input types areINPUT_GET
,INPUT_POST
,INPUT_COOKIE
,INPUT_SERVER
, orINPUT_ENV
.$var_name
is the name of the variable to check.
The filter_has_var()
function returns true
if the $var_name
exists in the $input_type
or false
otherwise.
The filter_has_var()
function only checks if a variable exists. It does not validate or sanitize the input. Typically, you’ll use the filter_has_var()
function with other functions like filter_input()
or filter_var()
to deal with security.
Checking a GET variable #
The following example uses the filter_has_var()
function to check if the term exists in the INPUT_GET:
<?php
if (filter_has_var(INPUT_GET, 'term')) {
echo "Term is set in GET: " . $_GET['name'];
} else {
echo "Term is not set.";
}
Code language: HTML, XML (xml)
Checking a POST variable #
The following example shows how to use the filter_has_var()
function to check if the email exists in INPUT_POST:
<?php
if (filter_has_var(INPUT_POST, 'email')) {
echo "Email is set: " . $_POST['email'];
} else {
echo "Email is not set.";
}
Code language: HTML, XML (xml)
filter_has_var vs. isset #
The isset()
function returns true
if a variable is declared and not null
. For example, the following checks if the name
variable in the $_POST
array:
<?php
if(isset($_POST['name'])) {
// process the name
}
Code language: PHP (php)
In this example, the isset()
checks if the $_POST
variable has a key 'name'
and the $_POST['name']
is not null.
However, the isset()
doesn’t check whether the name
variable comes from the HTTP request or not. For example:
<?php
$_POST['email'] = '[email protected]';
if(isset($_POST['email'])) { // return true
// ...
}
Code language: PHP (php)
In this example:
- First, manually set the
$_POST['email']
to a value. - Then, use the
isset()
function to check if theemail
variable exists.
As a result, the isset()
function returns true
.
Unlike the isset()
function, the filter_has_var()
function doesn’t read the contents of the $_POST
array. It checks the variables in the request’s body. Therefore, the following example returns false
:
<?php
$_POST['email'] = '[email protected]';
if(filter_has_var(INPUT_POST, 'email')) { // return false
// ...
}
Code language: PHP (php)
Summary #
- Use the
filter_has_var()
function to check if a variable exists in a specified type, includingINPUT_POST
,INPUT_GET
,INPUT_COOKIE
,INPUT_SERVER
, orINPUT_ENV
.