why i get an default output 0 after the invalid inputs? - php

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

Related

How $_POST in php operates

my index file is
<body>
<form method="POST" action="post.php" >
<input name="name">
<input type="submit" value="submit">
</form>
</body>
and post.php is
<?php
$sec = 'qaswed';
if($sec == $_POST['name'])
{
echo "true";
}
else
{
echo "false";
}
?>
When I am simply writing the TRUE in place of $_POST['name'] in post.php file then irrespective of what i submit in index file,the result is true as obvious i.e
if($sec == TRUE) { echo "true"; } else { echo "false"; }//true
But, When in index file if i send TRUE in the name parameter then why the output is coming false .. i.e
if($sec == $_POST['name']) { echo "true"; } else { echo "false"; }// false when name=TRUE
when I send this from other page variable (request) then it evaluates to false.why it happens?
When you write if ($sec == TRUE), then it's true, because you are using automatic type conversion with the == operator, and php converts the $sec string to bool type, where since it's not (bool)false(not string 'false'!!!!) or (int)0, it becomes true, and the true === true = true.
If you don't want the php to automatically convert the values in the if, then use === instead of ==, which will also check the type.
In the other case you are sending a "true" string and you have "qaswed" string which is obviously not the same, and since both of them are strings there are no type conversion like in the previous case.
In first comparison value of string 'qaswed' automatically is casted to the boolean value in order to comapre to the bool. When you compare different data types one of it is casted to another type.
If you want to compare also types of the variables you should use Identical Comparison Operator.
var_dump('qaswed'); // string(6) "qaswed"
var_dump((bool)'qaswed'); // bool(true)
var_dump('qaswed' == true); // bool(true)
var_dump('qaswed' === true); // bool(false)
In second case you compare string types.
var_dump('TRUE'); // string(4) "TRUE"
var_dump('qaswed'); // string(6) "qaswed"
var_dump('qaswed' == 'TRUE'); // bool(false)
var_dump('qaswed' === 'TRUE'); // bool(false)
i just added "if (isset($_POST['name']))" for checking the name is set or not
//post.php
<?php
if (isset($_POST['name']))
{
$sec = 'qaswed';
if ($sec == $_POST['name'])
{
echo "true";
}
else
{
echo "false";
}
}
?>

PHP testing user input for certin value range

I cant seem to figure out how to make a php if stament to tell if the user inputed a numeric value and in the certin range value.
<form name="heat.php" class="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Get The Heat Index</legend>
Tempeture <input type="text" name="temp"><br>
Humidity <input type="text" name="hum"><br>
<input id="submit"type="submit" value="Get The Heat Index">
</feildset>
</form>
<?php
$temp=
$hum="";
if (empty($temp) && empty($hum) && ("80" <= $temp) && ($temp >= "112") && ("13" <= $hum) && ($hum >= "85")) //validates temp input
{
echo "The temperature should be a number between 80 and 112.
The humidity should be a number between 13 and 85. Please try again.";
} else{
}
?>
Once user inputs the correct data the else will happen but if its not a correct number or outside of the range value then they will get the error message.
You can do it in one check - just use filter_var
Example:
filter_var(
$value,
FILTER_VALIDATE_INT,
[
'options' => [
'max_range' => 10,
'min_range' => 4
]
]
)
This will return the value as integer for all values passed in that are an integer and between 4 and 10. (both inclusive!). If the passed value does not fit the parameters, it will return false. If you do not want that false is returned you can specify a default return value:
filter_var(
$value,
FILTER_VALIDATE_INT,
[
'options' => [
'max_range' => 10,
'min_range' => 4,
'default' => 5
]
]
)
And the working code: https://3v4l.org/JZ54r
Here's code that works as follows:
<?php
const minHum = 13;
const maxHum = 85;
const minTemp = 80;
const maxTemp = 112;
$temp = 0;
$hum = 0;
$message = "";
$arrOptions = [["options" => ["min_range"=>minTemp, "max_range"=>maxTemp]],
["options" => ["min_range"=>minHum, "max_range"=>maxHum]]];
$arrShouldBe = ["The temperature should be a number between 80 and 112.",
"The humidity should be a number between 13 and 85. Please try again."];
function failed2Validate($var,$arr){
if ( filter_var($var, FILTER_VALIDATE_INT, $arr)== false) {
return true;
}
return false;
}
function validate($temp,$hum,$arrOptions, $arrShouldBe){
$i=0;
$message = "";
$arrFuncs = [failed2Validate($temp,$arrOptions[0]), failed2Validate($hum,$arrOptions[1])];
$count = count($arrFuncs);
while ($i < $count) {
$message = $arrFuncs[$i]? $arrShouldBe[$i]: "Success";
if ($message != "Success"){
break;
}
$i++;
}
return $message;
}
/******* START ******/
if ( isset( $_POST["submit"] ) ) {
if ( !isset($_POST['temp']) || !isset($_POST['hum']) ) {
$message = "No data, No dice";
}
// check that data is numeric
else
if( ctype_digit($_POST['temp']) && ctype_digit($_POST['hum']) ) {
[$temp,$hum] = [ $_POST['temp'], $_POST['hum']];
}
else
{ //coerce data into numeric values
[$temp,$hum] = [(int) $_POST['temp'], (int) $_POST['hum']];
}
if ($message != "No data, No dice") {
$message = validate($temp,$hum,$arrOptions, $arrShouldBe);
}
echo $message;
?>
<html>
<head><title>test</title>
</head>
<body>
<form name="myform" class="form" method="post" action="<?php echo $action; ?>">
<fieldset>
<legend>Get The Heat Index</legend>
Tempeture <input type="text" name="temp"><br>
Humidity <input type="text" name="hum"><br>
<input name="submit" id="submit"type="submit" value="Get The Heat Index">
</feildset>
</form>
</body>
</html>
See simulated POST with slightly modified PHP code here.
The name attribute of the OP's form seems oddly reminiscent if a PHP filename. So, I changed it to myform. More info about the name attribute in HTML form here.
One line of code, namely $temp= will produce a parser error. Interestingly, you may write a statement, like $temp;.
One needs to be careful with logic when using empty() vs isset() since with respect to a variable that has not been assigned a value or is set to null, empty() returns true unlike isset() which returns false.
Most importantly, user-submitted data should be treated as tainted. So, in this case, the code checks to see if the user submitted values. If so, then the data is tested to see whether it is numeric. If not, then the code casts the POST data to integers. In the OP's code sample there is no code indicating that POSTed data was assigned to any variables. In fact, the OP's code never tests that a form was even submitted, therefore I inserted code to test for that circumstance.
Lastly, the comparisons need the correct order, i.e. if a user enters 90 for the temperature then the test ("80" <= $temp) will always return true, but if you reverse the operands, i.e. ($temp <= "80") then you can detect accurately whether user submitted a temperature in the desired range or if an error has occurred.
Note: I originally revised my answer having been inspired by the example that kuh-chan provides using filter_var().

php check if values in form have been filled

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';
}

Why is $name field never !, even when empty?

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.

PHP form entry 0 returning NULL

// removed from original post
// if (!empty($_POST['user_inputA2'])) {
function formA2 () {
function test_input_A2($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form id="questionA2" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
<input type="text" name="user_inputA2" value="<?php if(isset($_POST['user_inputA2'])) { echo htmlentities ($_POST['user_inputA2']); }?>"/><br>
<input type="submit" name="user_inputA2Submit" style="position: absolute; left: -9999px"/>
</form>
<?php
if (!empty($_POST['user_inputA2']) && $_POST['user_inputA2'] !=="0") {
$user_inputA2 = test_input_A2($_POST["user_inputA2"]);
// more variables here, per line -- and add them to the ="" above.
return $user_inputA2;
}
}
UPDATE -- code below is what ended up working
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST['user_inputA2'] !="") {
$user_inputA2 = test_input_A2($_POST["user_inputA2"]);
// more variables here, per line -- and add them to the ="" above.
return $user_inputA2;
}
}
}
If I enter anything besides 0, my PHP code for !empty executes. I have tried alternatives of isset, !== NULL, and even an alternative IF statement of (... === "0" || ... === 0) { $user_inputA2 = "0" }. Still returns null and the page responds as if nothing was entered in the form.
How can I get the rest of the code to execute if the form entry is 0 (de facto isset or !empty) ?
You could try this:
<?php
// No need for this line
// if ($_SERVER["REQUEST_METHOD"] == "POST")
if(isset($_POST['user_inputA2']) && $_POST['user_inputA2'] !== '') {
$user_inputA2 = test_input_A2($_POST['user_inputA2']);
return $user_inputA2;
}
I found a fix on the receiving side. The code above does return the string of 0, but for implementation, I was asking if comparisons such as empty, !empty, isset. I changed those to if comparison either == "" or != "", and then the return value of 0 was treated as that actual value, etc.
Sorry the solution ended up being downstream in code from what I posted. Thanks again, everyone.

Categories