Ahmadz Issa
Ahmadz Issa

Reputation: 765

empty($_POST) === FALSE doesn't work as it should

I was testing the empty function in php, but it doesn't work, because the if statement is accessible whether the condition is false or true.

<?php
    if(empty($_POST) === false){

        echo 'text';
}
?>



<form action="index.php"  method="post">
    Username:
    <input type="text" name="text">
    <input type="submit" name="submit">
</form>

The echo is executed even if the input is empty.

Why ??

Upvotes: 2

Views: 1046

Answers (2)

al&#39;ein
al&#39;ein

Reputation: 1729

That's because $_POST will NEVER be empty after receiving a POST request from a form with input values inside it.

If you var_dump yours, you'll see:

textarray(2) { ["text"]=> string(0) "" ["submit"]=> string(12) "Submit Query" } 

Even your submit input is sent (as it is part of the form). And even without receiving anything, $_POST will return an empty set array, so neither isset is a good option to check POST fail or success.

You need to evaluate a specific field, like $_POST['text'], for emptiness instead.

Upvotes: 4

Ralph Melhem
Ralph Melhem

Reputation: 757

if(isset $_POST["text"] && $_POST["text"] !=null)

also, try using == instead of === == will cast the value of $_POST, so if it's NULL, it will be evaluated as false instead

Upvotes: 1

Related Questions