I tried to make a form with a post method, and i want to check if the fields are filled with isset(). But even if the fields are empty, the isset returns true.
Here is a simplified code: (name of the page: test.php, the post method is directed to itself)
if (isset($_POST['test'])) {
echo 'field set';
}
?>
<form method="post" action="test.php">
<input type="text" name="test"/>
<input type="submit" value="Submit"/>
</form>
When you submit, it always echoes 'field set', even if you didn't enter anything in the "test" input.
Thanks for your answers !
So check whether $_POST['test'] is empty or not and try like this
if (isset($_POST['test']) && trim($_POST['test']) != '') {
echo 'field set';
}
You can also use empty,but Note that "0" is also "empty" and along with it its better to trim the inputs to remove spaces. Another way is to check the length of input using strlen
if (isset($_POST['test']) && trim(strlen($_POST['test'])) > 0) {
echo 'field set';
}
try with empty() to check blank cause after submit form $_POST['test'] always found in isset() even it's blank. so need to check with empty()
if (!empty($_POST['test'])) {
echo 'field set';
}
0 would be empty/blank with checking empty()
You can do this with empty() method.try with this code.
ex : echo !empty($_POST['test']) ? "field set" : "" ;
It will echo that you field is set because all you are checking for if is the array key test exists with isset(). As long as you have a field in your form with the name test, it will create an empty key, thus resulting in it being set.
What you would rather like is to see if the key is set, and if the key also is empty or not.
This you can do by:
if( isset( $key['test'] ) && $key['test'] !== "" ){
//Do something
}
Related
I have this checkbox in my html
<input name="cb" class="cmn-toggle cmn-toggle-round" type="checkbox">
What I understood about how checkbox worked, was that when "checked" if you isset the input then it would "exist", and if wasn't "checked" wouldn't, so I did this:
if(isset($_REQUEST['cb'])){
//do something
}else{
//do something else
}
The problem is that when sending the form, it always exist, doesn't matter if checked or not, I don't know how to really see if really checked, so what am I doing wrong?
isset() determine if a variable is set and is not NULL. So in your case, the $_REQUEST['cb'] always exist, so isset() will be true. So if you have isset() in your condition, you need to add a check, if the value is true or false.
You need edit your condition to:
if($_REQUEST['cb']) { ...
or
if($_REQUEST['cb'] == true){ ...
and the best way is use isset with check above:
if( isset($_REQUEST['cb']) && $_REQUEST['cb'] == true ) { ...
You can check like this
if(isset($_REQUEST['cb']) && $_REQUEST['cb']){
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 ??
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.
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
I am trying simple web form action in PHP, whatever input given to in the input field output value is 1. and undefined index error for username, password when isset not present before the $_POST
<html>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit"></form>
</html>
<?php
$usernmae=isset($_POST["username"]);
$pass=isset($_POST["password"]);
echo $usernmae," ",$pass;
?>
<?php
/*** if else in a single statement ****/
$username = isset($_POST["username"]) ? $_POST["username"] : "";
$pass = isset($_POST["password"]) ? $_POST["password"] : "";
echo $username." - ".$pass;
?>
Dont use
$usernmae=isset($_POST["username"]);
$pass=isset($_POST["password"]);
Put only
$usernmae=$_POST["username"];
$pass=$_POST["password"];
Because isset() gives boolean values i.e. 1 or 0. In your case isset($_POST["username"]) checks that you have put values in this field or not. if there is some values in username field then it return 1 otherwise returns 0.
It should be
$usernmae= $_POST["username"];
$pass= $_POST["password"];
echo $usernmae," ",$pass;
isset($_POST["username"]) and isset($_POST["password"]) return 1 if evaluation is TRUE since isset() return boolean.
Others have told you how to solve the problem. I will tell you what the problem is.
Problems
You need to know following things:
PHP's boolean to string implicit conversion
When implicitly converting a boolean to a string, PHP acts a bit weird.
$testVar = false;
echo (string)$testVar; //will output a empty string (as that evaluates to false)
$testVar = true;
echo (string)$testVar; //will output 1 (as that evaluates to true)
How isset() works
According to the PHP Manual,
Returns TRUE if [variable supplied as argument] exists and has value other than NULL, FALSE otherwise.
What happens when you try to access a $_POST parameter
As you very well know, $_POST parameters are available to a PHP script when,
There is an HTML form, of which action attribute points to the PHP script
User submits the form, with or without data
If the name attribute of a field in the form was "username", you can access this information from the PHP script after the submission of the form like this:
$_POST["username"]
But if the PHP script that processes the $_POST parameters are in the same file as the HTML form, no $_POST parameters will be available to the script when it is initially accessed.
And if you tried to access $_POST parameters when there are none, the result is Undefined index.
What's happening here?
With the understanding of the above three things, we can deduce what's happening in your case.
When your file is loaded on the first time to the browser, PHP interpreter has to interpret it first. But on this first time, no $_POST variables are present. So when you try to access $_POST parameters, it will result in an Undefined index error.
When you wrap the $_POST["..."] expressions in an isset(), isset() will return FALSE, because the parameters are simply not there. Since FALSE is converted to empty string (""), your echo statement produces nothing visible.
When you submit the form, the isset() calls will return TRUE, because the $_POST parameters are present this time. And as described above, TRUE becomes "1" when converted to strings. Hence you get the output 1.
Solution
You must always check before you access $_POST parameters.
$username = "";
if (isset($_POST["username"])) {
$username = $_POST["username"];
}
Or shorthand:
$username = isset($_POST["username"]) ? $_POST["username"] : "";
Why you are using isset($_POST["username"])? The isset() function return false if testing variable contains a NULL value and true otherwise.
Try like
if(isset($_POST))
{
$usernmae=$_POST["username"];
$pass=$_POST["password"];
echo $usernmae," ",$pass;
}
You need to check if a value exists first. If you don't, you will get an error.
thus isset($_POST['VALUE'])
If it exists, get it. If not, set to "empty"
<html>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit"></form>
</html>
<?php
/**
* Created by PhpStorm.
* User: Devunne3
* Date: 25/09/14
* Time: 12:32
*/
$usernmae=isset($_POST["username"])?$_POST['username']:'';
$pass=isset($_POST["password"])?$_POST['password']:'';
echo $usernmae," ",$pass;
?>
Your problem is this line
$usernmae=isset($_POST["username"]);
$pass=isset($_POST["password"]);
You're saving the value of isset(), which is a boolean 0 or 1.
Since the 2 params are set you're getting the 1 (true).
You want to do this:
if(isset($_POST["username"])){
$usernmae = $_POST['username'];
}
and the same for the password.
Replace the bottom 3 lines with
$username=isset($_POST['username'])?$_POST['username']:'';
$pass=isset($_POST['password'])?$_POST['password']:'';
echo $username," ",$pass
The isset() returns boolean, whether the variable is set or not. That makes it return 1. In my answer if the field has value, it will echo the value if not, will echo blank string
try this. and the reason you you are getting 1 and 1, because you are using
$usernmae=isset($_POST["username"]);
That is one couase you set it.
if(!empty($_POST['submit'])){
$usernmae=$_POST["username"];
$pass=$_POST["password"];
echo $usernmae," ",$pass;
}
if(isset($_POST) && !empty($_POST))
{
$usernmae=$_POST["username"];
$pass=$_POST["password"];
echo "User Name is : ".$usernmae,"Password is : ".$pass;
}
The problem:
if i submit the html form and a textbox is left blank
then i don't want it to proceed to the echo segment,
but the problem is it does proceed.
<?php
if(!isset($_POST['submit']) && empty($_POST['moon']) && empty($_POST['planet']))
{
?>
<form name="form2" method="post" action="<?php echo($_SERVER["PHP_SELF"]);?>">
<div>
Write a planet name: <input name="planet" type="text"><br>
Its moon: <input name="moon" type="text">
</div>
<div>
<input type="submit" name="submit" value="submit">
</div>
</form>
<?php
}else{
echo("Planet: ".$_POST['planet']. "<br>");
echo("Moon: ". $_POST['moon'] . "<br>");
echo "Successful.";
}
?>
As you know isset() determines if a variable is set and not null but doesn't check if it's empty.
While logic seems my if statement, I modified it from:
if(!isset($_POST['submit']) && empty($_POST['moon']) && empty($_POST['planet']))
To:
if(!isset($_POST['submit']) && ($_POST['planet']=='') && ($_POST['moon']==''))
if(!isset($_POST['submit']))
if(!isset($_POST['planet']) && !isset($_POST['moon']))
if(empty($_POST['moon']) && empty($_POST['planet']))
and none of them worked.
So am I doing something wrong with my if statement? how can I not let it proceed to the Else segment while a textbox is empty? without more if and no nested statements please.
When you submit a form, the submit button will be set, so isset($_POST['submit']) will be true, therefore !isset($_POST['submit']) will be false.
When doing an if statement with the && comparison, all conditions must be true in order to execute that block of code, otherwise it goes to the else statement.
What you need to do is actually have 2 comparison checks. Once to see if the form was never submitted and one to see if it was, and the text boxes are empty:
<?php
// Check if form was submitted
if(!isset($_POST['submit'])
{
// Display the form
}
else
{
// Form was submitted, check if values are empty
if(trim($_POST['planet'])=="" || trim($_POST['moon'])=="")
{
// One or more value is empty, do something
}
else
{
// Process form
}
}
?>
I realize you are trying to avoid nesting, but in order for the logic to flow smoothly, and the code to remain readable, this is a necessary evil.
Change
if(!isset($_POST['submit']) && empty($_POST['moon']) && empty($_POST['planet']))
To
if(!isset($_POST['submit']) || (empty($_POST['moon']) || empty($_POST['planet'])))
Then if you submit with either textbox being empty, it will redisplay the form. If both textboxes have been filled in, you will see the else part.
Your problem is that if(!isset($_POST['submit'])) is always set when the form is submitted - so that is true. You also might want to change the && to ||. By using || you say OR, so say if anyone is empty, then do this, else do that.
I want to validate form fields when submitting the form, I use isset() to check if the field has a value or not. The problem I face that it returns true if the field has a value of does not !!!!!
here's HTML code
<form action="handler.php" method="post">
<label>userName: </label><input type="text" name="fname" /><br/>
</form>
and here's php code
<?php error_reporting(E_ALL);
if(validateForm()){?>
Welcome <?php echo $_POST["fname"]; ?>.<br />
}
function validateForm(){
$empty=false;
$empty=isset($_POST['fname'])?'true':'false';
echo 'empty>>>>'.$empty;
return $empty;
}
?>
What you want to use is empty :
function validateForm(){
return !empty($_POST['fname']);
}
edit : removed isset() as it wasn't necessary. Thanks to #Julian.
When your doing an input form, and the input textfield is empty, it's not NULL. isset checks if it's NULL or not. Returns true if not NULL and returns false if NULL.
I would check if it's empty, using empty(). It checks if the variable passed to it is empty or not. Returns true if empty, false if non empty.
Even if the field has no value, it is set with the value of "" (a string with the length 0). If you want to check if there is a value which is usable, either use empty() or check the length of the string.
use
isset($_POST['fname']) && !empty($_POST['fname'])
if not sure whats inside $_POST ,just print it
var_dump($_POST)