Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'].

like image 813
Spencer McCreary Avatar asked Feb 06 '12 01:02

Spencer McCreary


People also ask

Which function is used to check if $_ POST variable is empty?

Use the empty function to check if a variable contents something: <?

Why $_ POST is empty?

In my case, when posting from HTTP to HTTPS, the $_POST comes empty. The problem was, that the form had an action like this //example.com When I fixed the URL to https://example.com , the problem disappeared. I think is something related on how the server is setup. I am having the same issues using GoDaddy as a host.

How do you check if $post is empty?

You can check the existence of $ _POST with the empty() function. But, the empty() function will return true in the following cases: When all $_POST values are empty strings. The argument is zero.

Which of the following function is used to check that a post variable is set?

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.


1 Answers

isset() will return true if the variable has been initialised. If you have a form field with its name value set to userName, when that form is submitted the value will always be "set", although there may not be any data in it.

Instead, trim() the string and test its length

if("" == trim($_POST['userName'])){     $username = 'Anonymous'; }       
like image 176
Andy Avatar answered Oct 08 '22 18:10

Andy