[php] Check whether $_POST-value is empty

if(isset($_POST['submit'])) {
    if(!isset($_POST['userName'])) {
        $username = 'Anonymous';
    }      
    else $username = $_POST['userName'];
}

I cannot get the $username to be "Anonymous"? It is either blank or the value of $_POST['userName'].

This question is related to php if-statement string

The answer is


$username = filter_input(INPUT_POST, 'userName', FILTER_SANITIZE_STRING);
if ($username == '') {$username = 'Anonymous';}

Best practice - always filter inputs, sanitize string is ok, but you're better off using a custom callback function to really filter out what's not acceptable. Then check the now-safe variable if it is null/empty and if it is, set to Anonymous. Does not require 'else' statement as it was set if it existed on the first line.


Question: Check whether a $_POST value is empty.

Translation: Check to see if an array key/index has a value associated with it.

Answer: Depends on your emphasis on security. Depends on what is allowed as valid input.

1. Some people say use empty().

From the PHP Manual:

"[Empty] determines whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE."

The following are thus considered empty.

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

If none of these values are valid for your input control, then empty() would work. The problem here is that empty() might be too broad to be used consistently (the same way, for the same reason, on different input control submissions to $_POST or $_GET). A good use of empty() is to check if an entire array is empty (has no elements).

2. Some people say use isset().

isset() (a language construct) cannot operate on entire arrays, as in isset($myArray). It can only operate on variables and array elements (via the index/key): isset($var) and isset($_POST['username']). The isset()language construct does two things. First it checks to see if a variable or array index/key has a value associated with it. Second, it checks to make sure that value is not equal to the PHP NULL value.

In short, the most accurate check can be accomplished best with isset(), as some input controls do not even register with $_POST when they are not selected or checked. I have never known a form that submitted the PHP NULL value. None of mine do, so I use isset() to check if a $_POST key has no value associated with it (and that is not NULL). isset()is a much stricter test of emptiness (in the sense of your question) than empty().

3. Some people say just do if($var), if($myArray), or if($myArray['userName']) to determine emptiness.

You can test anything that evaluates to true or false in an if statement. Empty arrays evaluate to false and so do variables that are not set. Variables that contain the PHP NULL value also evaluate to false. Unfortunately in this case, like with empty(), many more things also evaluate to false: 1. the empty string '', zero (0), zero.zero (0.0), the string zero '0', boolean false, and certain empty XML objects.

--Doyle, Beginning PHP 5.3

In conclusion, use isset() and consider combining it with other tests. Example:

May not work due to superglobal screwiness, but would work for other arrays without question.

if (is_array($_POST) && !empty($_POST)) {
    // Now test for your successful controls in $_POST with isset()
} 

Hence, why look for a value associated with a key before you even know for sure that $_POST represents an array and has any values stored in it at all (something many people fail to consider)? Remember, people can send data to your form without using a web browser. You may one day get to the point of testing that $_POST only has the allowed keys, but that conversation is for another day.

Useful reference:

PHP Manual: Type Testing Comparison Tables


If the form was successfully submitted, $_POST['userName'] should always be set, though it may contain an empty string, which is different from not being set at all. Instead check if it is empty()

if (isset($_POST['submit'])) {
    if (empty($_POST['userName'])) {
        $username = 'Anonymous';
    } else { 
        $username = $_POST['userName'];
    }
}

Change this:

if(isset($_POST['submit'])){

    if(!(isset($_POST['userName']))){
    $username = 'Anonymous';
    }      
    else $username = $_POST['userName'];
}

To this:

if(!empty($_POST['userName'])){
     $username = $_POST['userName'];
}

if(empty($_POST['userName'])){
     $username = 'Anonymous';
}

To check if the property is present, irrespective of the value, use:

if (array_key_exists('userName', $_POST)) {}

To check if the property is set (property is present and value is not null or false), use:

if (isset($_POST['userName'])) {}

To check if the property is set and not empty (not an empty string, 0 (integer), 0.0 (float), '0' (string), null, false or [] (empty array)), use:

if (!empty($_POST['userName'])) {}

i'd use a simple one line comparisant for these use cases

$username = trim($_POST['userName'])?:'Anonymous';

This is for the use case you are certain error logging is off so you don't get a warning that the variable isn't initialised.

this is the paranoid version:

$username = !empty(trim(isset($_POST['userName'])?$_POST['userName']:''))?$_POST['userName']:'Anonymous';

This implements a check if the $_POST variable is set. before accessing it.


isset is testing whether or not the key you are checking in the hash (or associative array) is "set". Set in this context just means if it knows the value. Nothing is a value. So it is defined as being an empty string.

For that reason, as long as you have an input field named userName, regardless of if they fill it in, this will be true. What you really want to do is check if the userName is equal to an empty string ''


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to if-statement

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript