111

I have a form on one page that submits to another page. There, it checks if the input mail is filled. If so then do something and if it is not filled, do something else. I don't understand why it always says that it is set, even if I send an empty form. What is missing or wrong?

step2.php:

<form name="new user" method="post" action="step2_check.php"> 
    <input type="text" name="mail"/> <br />
    <input type="password" name="password"/><br />
    <input type="submit"  value="continue"/>
</form>

step2_check.php:

if (isset($_POST["mail"])) {
    echo "Yes, mail is set";    
} else {    
    echo "N0, mail is not set";
}
SharpC
  • 6,974
  • 4
  • 45
  • 40
Nrc
  • 9,577
  • 17
  • 67
  • 114
  • 6
    All text-like inputs and textareas present in your form will be submitted to the server even if their values are empty strings. – hypeJunction May 26 '16 at 09:28

15 Answers15

236

Most form inputs are always set, even if not filled up, so you must check for the emptiness too.

Since !empty() is already checks for both, you can use this:

if (!empty($_POST["mail"])) {
    echo "Yes, mail is set";    
} else {  
    echo "No, mail is not set";
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
oopbase
  • 11,157
  • 12
  • 40
  • 59
  • 11
    This comparison table is very helpful for things like this http://php.net/manual/en/types.comparisons.php – A Star Jun 04 '13 at 22:16
  • 2
    Minor thing... I think it's preferable to avoid the `!` operator in cases like this (easier to read, less chance of error, etc.) and reverse the logic... `if (empty()) {/* No */} else {/* Yes */}` – MrWhite Aug 01 '14 at 10:58
  • I don't see why it would be preferrable to avoid `!empty()`. I will admit, though, that I prefer to write failing conditions before successful conditions. – mickmackusa Mar 12 '21 at 15:01
  • Caution though, and not fall in the habit of always comparing with empty. This works well in the case of the email, but if you expect the user could input 0 (as integer or string) empty will return TRUE. – kissumisha Apr 28 '22 at 02:10
27

Use !empty instead of isset. isset return true for $_POST because $_POST array is superglobal and always exists (set).

Or better use $_SERVER['REQUEST_METHOD'] == 'POST'

Nemoden
  • 8,816
  • 6
  • 41
  • 65
  • 3
    You should mention that use BOTH `isset` and `!empty` to prevent error. EDIT: Whoops, it does apparently Learning every day then [Ref](http://kunststube.net/isset/) – Touki Oct 24 '12 at 08:19
  • 1
    I tried and both works fine. Why is $_SERVER['REQUEST_METHOD'] == 'POST' better? What does it exactly do? can it refers to a specific input or it is generic to the form? – Nrc Oct 24 '12 at 08:55
  • 3
    `$_SERVER['REQUEST_METHOD']` ensures user has submitted form. `$_POST` can be empty even in this case. Consider this form: `
    `, submitting it will send nothing to the action, but request type will be `post`. Or it can be done with curl: `curl -X POST http://example.com/processor.php`. If processor contains code like `echo $_SERVER['REQUEST_METHOD']. ' '.var_export(empty($_POST),1);`, you will see `POST true`
    – Nemoden Oct 25 '12 at 01:28
  • `isset()` can be appropriate when you specify a key within `$_POST` AND want to allow a falsey value like `0`. Particular to email value submissions, using `!empty()` is an inadequate tool to validate an email address. – mickmackusa Mar 12 '21 at 15:04
5

From php.net, isset

Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

empty space is considered as set. You need to use empty() for checking all null options.

janenz00
  • 3,315
  • 5
  • 28
  • 37
4

If you send the form empty, $_POST['mail'] will still be sent, but the value is empty. To check if the field is empty you need to check

if(isset($_POST["mail"]) && trim($_POST["mail"]) != "") { .. }
SharpC
  • 6,974
  • 4
  • 45
  • 40
mboldt
  • 1,780
  • 11
  • 15
2

You can simply use:

if($_POST['username'] and $_POST['password']){
  $username = $_POST['username'];
  $password = $_POST['password'];
}

Alternatively, use empty()

if(!empty($_POST['username']) and !empty($_POST['password'])){
  $username = $_POST['username'];
  $password = $_POST['password'];
}
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • According with the [PHP type comparison tables](http://php.net/manual/en/types.comparisons.php) you are absolutely right. A simple boolean does the work of the empty function to check the empty string. – viery365 Dec 07 '17 at 21:44
  • I know this is old answer but first method can cause undefined index notice. – ICE Nov 28 '18 at 00:57
  • 1
    @ICE It can be easily bypassed by prefixing the variables with `@`,i.e: `@$_POST['username']`. Thank you for noticing that. – Pedro Lobito Nov 28 '18 at 01:09
  • `@` often makes code look unprofessional. Handle notices and warnings properly. – mickmackusa Mar 12 '21 at 15:20
1

Add the following attribute to the input text form: required="required". If the form is not filled, it will not allow the user to submit the form.

Your new code will be:

<form name="new user" method="post" action="step2_check.php"> 
<input type="text" name="mail" required="required"/> <br />
<input type="password" name="password" required="required"/><br />
<input type="submit"  value="continue"/>
if (isset($_POST["mail"])) {
    echo "Yes, mail is set";    
}
WillS
  • 362
  • 1
  • 12
Kushan Mehta
  • 190
  • 3
  • 11
  • Relying on client-side validation is not enough. It is trivial to manually circumvent client-side defenses. For improved security, strong validations need to be implemented on the server-side. As stated elsewhere on this page `isset()` will not work as required by the OP. – mickmackusa Mar 12 '21 at 15:09
  • I totally agree. Wrote this answer a long back. This answer suggests the frontend side of things. Ideally validation should be done both in the frontend and the backend with error passing from server side and handling the error on the frontend. – Kushan Mehta Mar 13 '21 at 17:05
  • Bottomline to researchers: this answer's server-side check does not ensure that the form field is filled in. – mickmackusa Mar 13 '21 at 20:45
0

Maybe you can try this one:

if (isset($_POST['mail']) && ($_POST['mail'] !=0)) { echo "Yes, mail is set"; } else { echo "No, mail is not set"; }

Nica
  • 177
  • 4
  • 17
  • This is more simply written as `!empty()`. It also makes your snippet less intuitive by checking for _not zero_ on an email field's value. – mickmackusa Mar 15 '21 at 10:59
0
<?php
    if(isset($_POST['mail']) && $_POST['mail']!='') {
        echo "Yes, mail is set";
    }else{
        echo "N0, mail is not set";
    }
?>
Asep Nurjaman
  • 156
  • 11
0

Lets Think this is your HTML Form in step2.php

step2.php

<form name="new user" method="post" action="step2_check.php"> 
    <input type="text" name="mail"/> <br />
    <input type="password" name="password"/><br />
    <input type="submit"  value="continue"/>
</form>

I think you need it for your database, so you can assign your HTML Form Value to php Variable, now you can use Real Escape String and below must be your

step2_check.php

if(isset($_POST['mail']) && !empty($_POST['mail']))
{
$mail = mysqli_real_escape_string($db, $_POST['mail']);
}

Where $db is your Database Connection.

  • `isset()` followed by `!empty()` is an antipattern that should not exist in any code for any reason. It is doing too much work. If `!empty()` is the desired logic, then also checking `isset()` is pointless. Also, do not use `mysqli_real_escape_string` anymore; use prepared statements. – mickmackusa Mar 15 '21 at 11:00
0

Check to see if the FORM has been submitted first, then the field. You should also sanitize the field to prevent hackers.

form name="new user" method="post" action="step2_check.php"> 
    <input type="text" name="mail"/> <br />
    <input type="password" name="password"/><br />
    <input type="submit"  id="SubmitForm" name= "SubmitForm" value="continue"/>
</form>

step2_check:


if (isset($_POST["SubmitForm"]))
   {
   $Email =  sanitize_text_field(stripslashes($_POST["SubmitForm"]));
   if(!empty($Email))
     echo "Yes, mail is set"; 
   else
     echo "N0, mail is not set";
   } 
}

Debbie Kurth
  • 403
  • 3
  • 16
  • See how you are unconditionally declaring `$Email` before checking if it is not empty? This is doing unnecessary work. `!empty()` does two things. It checks if a variable is declared and checks if it is truthy. Since the variable is certainly declared, you can just use `if ($Email) {` with the exact same effect. – mickmackusa Mar 12 '21 at 11:03
-1

To answer the posted question: isset and empty together gives three conditions. This can be used by Javascript with an ajax command as well.

$errMess="Didn't test";   // This message should not show
if(isset($_POST["foo"])){ // does it exist or not
    $foo = $_POST["foo"]; // save $foo from POST made by HTTP request
    if(empty($foo)){      // exist but it's null
        $errMess="Empty"; // #1 Nothing in $foo it's emtpy

    } else {              // exist and has data
        $errMess="None";  // #2 Something in $foo use it now
      }
} else {                  // couldn't find ?foo=dataHere
     $errMess="Missing";  // #3 There's no foo in request data
  }

echo "Was there a problem: ".$errMess."!";
Vinnarian
  • 1
  • 1
-1

You can try this:

if (isset($_POST["mail"]) !== false) {
    echo "Yes, mail is set";    
}else{  
    echo "N0, mail is not set";
}
Machavity
  • 30,841
  • 27
  • 92
  • 100
akash ujjwal
  • 174
  • 2
  • 14
-1
<form name="new user" method="post" action="step2_check.php"> 
  <input type="text" name="mail" required="required"/> <br />
  <input type="password" name="password" required="required"/><br />
  <input type="submit"  value="continue"/>
</form>

<?php
if (!empty($_POST["mail"])) {
    echo "Yes, mail is set";    
}else{  
    echo "N0, mail is not set";
}
?>
Thilina
  • 93
  • 2
  • 7
  • This advice was given years earlier https://stackoverflow.com/a/13045314/2943403 and adds no new value to the page. – mickmackusa Mar 15 '21 at 10:52
-1

You can try,

 <?php

     if (isset($_POST["mail"])) {
            echo "Yes, mail is set";    
        }else{  
            echo "N0, mail is not set";
        }
  ?>
Vimukthi Guruge
  • 285
  • 3
  • 15
-1

$-POST METHOD: if we use POST method in the form tag to pass data,we can find data in the server using $_POST array.using this array name we fetch data from server.($_POST['name'])Information sent from a form with the POST method is invisible to others(all names/values are embedded within the body of the HTTP request) and has no limits n the amount of information to send. Example Code:

<html>
<head>
</head>
<body>
<?php
if(isset($_POST['submit']))
{if(isset($_POST['name']) && isset($_POST['roll']))
{echo"<h1>form submitted</h1>";echo"your name is". $_POST['name']."<br>";
echo "your roll number is". $_POST['roll']."<br>";}}
else{?>
<form action="" method="POST">
Name:<input type="text" name="name"><br><br>
Roll:<input type="text" name="roll"><br>
<br><input type="submit" value="submit" name="submit">
</form>
<?php}?>
</body>
</html>
Moix Khan
  • 9
  • 4