I have a basic sign up form, and when checking if a field is not set (if(!$name)) it always goes to 'else', even when the field is empty.
Does anyone know why?
(When i'm trying to check it in reverse (if($name)), it does show the error line. )
*var_dump($name) - always returns a string, never false. I'm guessing thats part of the problem?...
Thanks a lot!!
<?php
$error = '';
if(isset($_POST['submit'])){
$name = trim(filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING));
if( !$name && preg_match("/^([\w]){2,50}$/", $name)){
$error = ' * Please enter a valid name';
}
?>
<form action="" method="post">
<label for="name">Name:</label><br>
<input type="text" name="name"> <br><br>
<input type="submit" name="submit" value="Sign up">
<span class="error"><?= $error ?></span>
</form>
Well, you got wrong IF statement. You are checking if $name is false (it will be only if you send empty string) AND if it's length is between 2-50.
Consider two states:
<?php
$name = 'Login';
$a = !$name; // FALSE! You're variable is OK, but you neg it
$b = preg_match("/^([\w]){2,50}$/", $name); // TRUE! Between 2-50 letters
<?php
if($a && $b) {
die("Won't be visible, because $a and $b are not the same");
}
And second:
$name = '';
$a = !$name; // TRUE! You're variable is empty, but you neg it
$b = preg_match("/^([\w]){2,50}$/", $name); // FALSE! has 0 letters
if($a && $b) {
die("Won't be visible, because $a and $b are not the same");
}
So, you should use OR instead of AND or just forget about first statement (second is checking same thing!):
<?php
if(!preg_match("/^([\w]){2,50}$/", $name)){
$error = ' * Please enter a valid name';
}
You're getting that undefined variable notice because you're trying to echo something in your form that hasn't already been set/not empty and your PHP/HTML form are used in the same file.
Sidenote: <?= is short tag syntax for "echo".
So change:
<?= $error ?>
to and with a conditional statement:
<?php if(!empty($error)) { echo $error; } ?>
or:
<?php if(isset($error)) { echo $error; } ?>
Or use a ternary operator:
http://php.net/manual/en/language.operators.comparison.php
or add an else to my suggestion above.
Plus, you also have a missing brace in your PHP (least, for what you posted) and that alone should have thrown you an unexpected end of file error.
Edit:
The reason that it is failing is the operator you're using, being && (AND). Use || (OR), to check if either one failed the criteria and not both. You're checking if there's no name AND if there's enough valid characters.
if( !$name || preg_match("/^([\w]){2,50}$/", $name))
and that's all it was, a simple wrong choice of operator.
Btw, my edit wasn't based on the other answer given. I actually was busy testing this out when that was posted.
Their explanation is well-written/explained, however they're working too hard.
Changing && to || in your code would have worked just fine.
Related
I have a form and php that submits the values, how do I make the php to check if the values are not empty?
Server code
$XX = mysqli_real_escape_string($link, $_REQUEST['XX']);
$YY = mysqli_real_escape_string($link, $_REQUEST['YY']);
if(empty($XX) || empty($YY))
{
echo "You need to fill in XX or YY";
}
Form markup:
<form method="POST" action="">
<label for="XX">XX</label><br>
<label for="YY">YY</label><br>
<input type="text" name="XX" id="XX"><br>
<input type="text" name="YY" id="YY"><br>
<input class="button" type="submit" value="submit"><br>
</form>
Assuming you are trying to check that at least one of these inputs has been set as your echoed message suggests then you need to use an and && and not an or || like this
if(empty($XX) && empty($YY))
{
echo "You need to fill in XX or YY";
}
PHP has three useful functions to test the value of a variable, you need to understand how these functions work in order to use them properly, below is a short description for each, hope it helps
isset()
Determines if a variable is set and is NOT NULL
So if the value assigned is "" or 0 or “0” or false the return will be true, if is NULL it will return false.
$var = '';
if(isset($var)) {
echo 'The variable $var is set.';
}
unset($var);
if(!sset($var)) {
echo 'The variable $var is not set';
}
Empty()
Determines if a variable is empty
So if the value is "" or 0 or 0.0 or "0" or NULL or False or [] it will return true
$var = '';
if(empty($var)) {
echo 'The variable $var is empty or not set';
}
is_null()
It returns true only if a variable is NULL.
$var = NULL;
if(is_null($var)) {
echo 'The variable $var is NULL';
}
if(is_null($foo)) {
echo 'The variable $foo is inexistent so the value is NULL and will evaluate to true';
}
My requirement is to set two values in an html form and pass those values into an PHP file where i will check wither these value is set or not set.If any one or two of the field is blank than it will show invalid input. And if the values are set (including 0) than it will do some action like as adding operation.But the problem is that if i set 0 it takes the value as empty value than shows invalid and also shows 0 after the invalid input. is this because add method is called.any explanation ?
please anyone help me to understand it clearly and also release me from the confusion of 0 and empty check.
My code is here,
HTML:
<input type="number" name="num1"">
<input type="number" name="num2">
<input type="submit" name="add" value="+">
PHP:
<?php
class calculator_oop
{
public $num1;
public $num2;
public $result;
public function __construct($number1,$number2){
if( ((empty($number1) || empty($number2)))) {
echo "Invalid inputs ";
}
else{
$this->num1 = $number1;
$this->num2 = $number2;
}
}
public function add(){
return $this->result = $this->num1 + $this->num2;
}
}
$ob = new calculator_oop($_POST['num1'],$_POST['num2']);
if($_POST['add'] =='+' ){
echo $ob-> add();
}
When I keep the field blank, I just wanna know why 0 appears after invalid input when I let them blank.
output:
Invalid input 0
What's happening here is, 0 is considered as being empty (consult the reference on this below), but you've also (or may have) entered 0 in the input(s), to which in the eye of PHP and at the time of execution, is considered as being "not empty" at the same time, since the input(s) was/were not left "empty" which is sort of fighting for precedence/contradicting itself at the same time.
What you want/need to check is to see if it/they is/are numeric or not by using is_numeric() and using another conditional statement, rather than in one condition in the second statement.
Additionally, you could add an extra condition to check if the inputs are left empty, and adding required to each input, but don't rely on this solely.
if( (!isset($number1,$number2 ))
|| !is_numeric($number1)
|| !is_numeric($number2) ) {
echo "Invalid input ";
}
References:
http://php.net/empty
In php, is 0 treated as empty?
NOTE:
Edit: After revisiting the question and during the time I was writing this, noticed you have posted your form.
Since you did not post your HTML form, this is the following that it was tested with:
<?php
// https://stackoverflow.com/q/41418885/
class calculator_oop
{
public $num1;
public $num2;
public $result;
public function __construct($number1,$number2){
// if( (!isset($number1,$number2 )) || (empty($number1 || $number2))) {
if( (!isset($number1,$number2 )) || !is_numeric($number1) || !is_numeric($number2) ) {
echo "Invalid input ";
}
else{
$this->num1 = $number1;
$this->num2 = $number2;
}
}
public function add(){
return $this->result = $this->num1 + $this->num2;
}
}
if(isset($_POST['submit'])){
$ob = new calculator_oop($_POST['num1'],$_POST['num2']);
if($_POST['add'] =='+' ){
echo $ob-> add();
}
}
?>
<form action="" method="post">
Number 1:
<input type="text" name="num1">
<br>
Number 2:
<input type="text" name="num2">
<br>
<input type="text" name="add" value="+" readonly>
<br>
<input type="submit" name="submit" value="Submit">
</form>
In PHP, the following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
if you want to test zero use :
$var == 0
or
$var == "0"
you have to understand this :
<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
?>
Please read : http://php.net/manual/en/function.empty.php
I've got the following line of code in PHP at the top of the page making sure all form fields have content in them and not submitted empty...
if(!isset($_POST['name'])) { $err_name = 1; }
if (!isset($_POST['phone'])) { $err_phone = 1; }
if (!isset($_POST['email'])) { $err_email = 1; }
if ((!isset($_POST['serve'])) && ($_POST['other'] == "")) { $err_serve = 1; }
name is a text input
email is a text input
phone is a text input
serve is a checkbox array
other is a text input
Then below that I've got the following lines which allow the php code to continue if there are no errors (above)
if (($err_name != 1) && ($err_phone != 1) && ($err_email != 1) && ($err_serve != 1)) {
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$phone = $_POST['phone']; // required
$serve = $_POST['serve'];
$other = $_POST['other'];
Then I've got this next to each form field...
<?php if ($err_name == 1) { echo '<font color="red">Name cannot be empty</font>'; } ?>
<?php if ($err_phone == 1) { echo '<br /><font color="red">Phone cannot be empty</font>'; } ?>
<?php if ($err_email == 1) { echo '<font color="red">Email cannot be empty</font>'; } ?>
<?php if($err_serve == 1) { echo '<br /><font color="red">You must choose at least 1 area to serve</font>'; } ?>
Can someone please help me figure out WHY its doing the following...
if I take && ($err_serve != 1) out of the 2nd code, everything
except phone shows error messages
if I leave it in, ONLY err_serve throws error. The others are
ignored and no error is displayed.
Phone refuses to throw error messages. This is everything where $_POST
handling is in the php.
Note that all tests are done by submitting a completely empty form
The values will be set whether or not they are filled with a value. If it's an empty value, it's still a value.
Instead of using isset(), use empty(). It checks both if:
The value exists at all
The value is something other than 0, an empty string, false, etc.
The reason it works for the checkbox, is because when a checkbox is not checked, the browser does not send the value at all. This is contrary to text fields. A browser will send the value of a text field whether or not it's empty.
http://ca2.php.net/manual/en/function.empty.php
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I've been figuring out how to do this but it seems not to be working.
My code for the form:
<form name="register" method="POST" action="php\reg.php">
<label>Email:</label>
<input type="email" name="email"/>
.
.
.
</form>
Code for the "reg.php" file:
if (isset($_POST['email'])) {
echo "success!";
} else {
echo "empty!";
}
?>
Problem is, whenever I input or not in the email textbox, isset function always returns the true value. how can I resolve this??
All answers that tell you about using isset() and empty() to check form values are... bad. Use one of the filter functions to check if a POST/GET/COOKIE variable is present and validate or sanitize it. Here is an example:
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
if ($email === NULL) {
die("Email field not present in form");
} elseif ($email === FALSE) {
die("Email is present but its value is invalid");
}
Note: the empty() function has a gotcha and I would not recommend using it for form validation unless you understand exactly what it does: it returns true for all falsy values. This means 0 is considered empty which is often an acceptable value in certain cases. Example (bad one):
if (empty($_POST["number_of_children"])) {
// triggers even when user enters 0
die("number of children field is empty");
}
isset() checks if the values is set, so it's true even if the value is empty string. Use empty():
if (empty($_POST['email']) == false) {
echo "success!";
}else{
echo "empty!";
}
<?php
if (!empty($_POST['email'])) {
echo "success!";
}else{
echo "empty!";
}
?>
try this-
<?php
if (!empty($_POST['email'])) {
echo "success!";
}else{
echo "empty!";
}
?>
Null and/or empty strings are still set if the variable is declared.
$_POST contains empty string for your value, and isset() returns true. Use empty() or add != '' in your if condition.try this:
if (!empty($_POST['email']))
Try to use empty() function to check if there is anything in email filed of $_POST array.
The example code based on your code is below:
<?php
if (isset($_POST['email']) && !empty($_POST['email'])) {
echo "success!";
} else {
echo "empty!";
}
?>
<?php
if (isset($_POST['email']) && $_POST['email'] != "") {
echo "success!";
}else{
echo "empty!";
}
?>
try this way
As simple as it seems, I dont know why this isn't working.
I have a form with a few drop down selects that if $message_type is equal to other, the message is constructed out of just the details from $details.
If $message_type is anything else, it should string together a message.
The variables are being passed and have checked that it is exactly 'Other' that is being passed through to the page using echo's so there is no spelling mistake.
At the moment, whatever the message type, it always just creates the message to be just $details and does not follow the 'else' line if it does not equal 'Other'.
if ($message_type = 'Other'){$message = $details;
}
else {$message = "Action to do: ".$message_type." On ".$user." Extra Details: ".$details;
}
Any help as this is now really confusing me.
Thanks
if ($message_type == 'Other')
{
$message = $details;
}
else
{
$message = "Action to do: ".$message_type." On ".$user." Extra Details: ".$details;
}
$message_type = 'Other' is alway true
What you did wrong were already explained by the other answer, but "why" does this happen? It's simple: = is the assignment operator and like any other operator in PHP (and many (all?) languages) the operator has a retun value, that is in this case the value of the assignment. PHP now cast this to a boolean and therefore it is true
if ($message_type = 'Other'){ /* .. */}
if ('Other'){ /* .. */}
if (true){ /* .. */}
if ($message_type = 'Other'){$message = $details;
}
else {$message = "Action to do: ".$message_type." On ".$user." Extra Details: ".$details;
}
you have if ($message_type = 'Other')
you should have if ($mesage_type == 'Other')
I suppose it is just writing mistake, so I wont be telling what is the diferance :)
You need two equal signs
if ($message_type == 'Other') {
-------------------^
$message = $details;
} else {
$message = "Action to do: ".$message_type." On ".$user." Extra Details: ".$details;
}
One equal sign is the assignment operator, so you are saying "$message_type is equal to 'Other'" instead of "if $message_type is equal to 'Other'"