If isset $_POST
Asked Answered
C

15

112

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";
}
Carhart answered 24/10, 2012 at 8:16 Comment(1)
All text-like inputs and textareas present in your form will be submitted to the server even if their values are empty strings.Neolithic
S
237

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";
}
Spoliation answered 24/10, 2012 at 8:19 Comment(4)
This comparison table is very helpful for things like this php.net/manual/en/types.comparisons.phpPryce
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 */}Guarded
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.Mountford
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.Elegit
C
28

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'

Cymose answered 24/10, 2012 at 8:18 Comment(4)
You should mention that use BOTH isset and !empty to prevent error. EDIT: Whoops, it does apparently Learning every day then RefDisherison
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?Carhart
$_SERVER['REQUEST_METHOD'] ensures user has submitted form. $_POST can be empty even in this case. Consider this form: <form method="post"></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 trueCymose
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.Mountford
H
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.

Horthy answered 24/10, 2012 at 8:20 Comment(1)
I find "for checking all null options" to be either too vague or misleading to researchers.Mountford
F
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"]) != "") { .. }
Feaster answered 24/10, 2012 at 8:19 Comment(2)
I copy paste the code and I think it does not work? Have you check it?Carhart
For the record, if(isset($_POST["mail"]) && trim($_POST["mail"])) { would do the same thing.Mountford
M
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'];
}
Maximo answered 30/4, 2015 at 14:26 Comment(4)
According with the PHP type comparison tables you are absolutely right. A simple boolean does the work of the empty function to check the empty string.Wakeup
I know this is old answer but first method can cause undefined index notice.Tomblin
@Tomblin It can be easily bypassed by prefixing the variables with @,i.e: @$_POST['username']. Thank you for noticing that.Maximo
@ often makes code look unprofessional. Handle notices and warnings properly.Mountford
Q
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";    
}
Quanta answered 9/10, 2014 at 17:8 Comment(3)
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.Mountford
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.Quanta
Bottomline to researchers: this answer's server-side check does not ensure that the form field is filled in.Mountford
D
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"; }

Dendro answered 1/10, 2014 at 3:34 Comment(1)
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.Mountford
C
0
<?php
    if(isset($_POST['mail']) && $_POST['mail']!='') {
        echo "Yes, mail is set";
    }else{
        echo "N0, mail is not set";
    }
?>
Ciceronian answered 10/11, 2017 at 7:23 Comment(2)
You should explain why your code answers the OP's question.Kristalkristan
As well as why you do not simply recommend !empty().Mountford
I
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.

Ingleside answered 4/4, 2019 at 19:9 Comment(1)
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.Mountford
I
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";
   } 
}

Illfated answered 25/10, 2019 at 21:26 Comment(1)
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.Mountford
B
-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."!";
Brieta answered 5/4, 2015 at 15:49 Comment(1)
empty() is doing too much work here because $foo is guaranteed to be declared when it is checked.Mountford
S
-1

You can try this:

if (isset($_POST["mail"]) !== false) {
    echo "Yes, mail is set";    
}else{  
    echo "N0, mail is not set";
}
Singly answered 26/9, 2015 at 20:21 Comment(2)
You need to explain your answer. SO exists to not just answer questions but to educate peopleProkofiev
This answer does not check that the submitted email is not email.Mountford
M
-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";
}
?>
Magness answered 11/7, 2016 at 7:31 Comment(1)
This advice was given years earlier https://mcmap.net/q/193876/-if-isset-_post and adds no new value to the page.Mountford
T
-1

You can try,

 <?php

     if (isset($_POST["mail"])) {
            echo "Yes, mail is set";    
        }else{  
            echo "N0, mail is not set";
        }
  ?>
Tallboy answered 10/5, 2017 at 13:36 Comment(1)
This answer does not validate that $_POST["mail"] is non-empty.Mountford
P
-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>
Proposal answered 16/1, 2021 at 17:22 Comment(1)
Not only does this answer ignore the OP's scenario, this answer does nothing to check if a field is "filled".Mountford

© 2022 - 2024 — McMap. All rights reserved.