PHP form entry 0 returning NULL - php

// 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.

Related

Zero considered as empty in PHP

I've got a problem with an input field in my php form. It looks like:
<input type="number" name="tmax" max="99" min="-99" placeholder="Temperatura max.">
I want to check whether the field is empty or not. But the problem is php considers 0 as empty.
if (empty($_POST['tmax'])) {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
If the user leaves the input field empty the value is considered as 'null', which works perfectly. But if the user writes 0, which is a possibility in the form, it is also treated as empty.
I've also set the default as null in SQL but the problem is, if the input is empty, the program inserts 0 in the table.
SOLUTION:
This solution works fine for me:
if ($_POST['tmax'] == "") {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
And also with is_numeric()
if (is_numeric($_POST['tmax'])) {
$tmax = $_POST['tmax'];
}else {
$tmax = 'null';
}
Check if the condition is empty, and also not zero. A zero-value is "empty", so by adding both checks, you ensure that the variable $tmax will be set to null if the input was empty and not zero.
if (empty($_POST['tmax']) && $_POST['tmax'] != 0) {
$tmax = null;
} else {
$tmax = $_POST['tmax'];
}
This will also accept "foo" as a value, so you should check or validate that the input is a valid number (and also in the ranges you specified). You can also implement is_numeric($_POST['tmax']), or even better, validate it with filter_var($_POST['tmax'], FILTER_VALIDATE_INT) to ensure that whatever was input is actually a number.
PHP.net on empty()
PHP.net on is_numeric()
PHP.net on filter_var()
PHP.net on flags for usage in filter_var()
As you state, 0 is considered empty.
The function you want is isset().
if (!isset($_POST['tmax'])) {
$tmax = null;
} else {
$tmax = $_POST['tmax'];
}
Alternatively, remove the not operator and switch the code blocks.
This code should work for what are you trying to get.
if (!isset($_POST['tmax']) || $_POST['tmax'] == '') {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
You can use !is_numeric() instead empty()
thanks for such a important note, Rafa
if you want to have placeholder - you can use this code:
<input type="number" name="tmax" max="99" min="-99" onclick="if (this.value == '') {this.value='0';} " placeholder="Temperatura max.">
don't forget add validation (before send form check on empty fileds )
and php to:
$tmax = 0;
if (isset($_POST['tmax'])) {
$tmax = $_POST['tmax'];
}
you may use
if ($_POST['tmax'] == "") {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}

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

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

php openssl_encrypt - always getting some strange output when idle

Having a trouble with openssl_encrypt function. I made encoder/decoder what takes input from one form and place output into another. With folowing code everything works BUT I'm getting always some output in the beginning even when no parameters are in forms/variables. When I fill forms, evertything works perfect. I made reseach and spend whole evening on this but nothing so far... (...atleast I learned other PHP things:)
<?php
$encode = $_POST["encode"];
$saltE = $_POST["keyE"];
$ivE = $_POST["ivE"];
$encrypt_method = "AES-256-CBC";
if ($encode === "" && $saltE === "") {
$warningE = "You forgot to enter text";
} elseif (!($encode === "") && !($saltE === "") && !($ivE === "")) {
$encoded = openssl_encrypt($encode, $encrypt_method, $saltE, 0, $ivE);
} elseif (!($encode === "") && ($saltE === "")) {
$warningEE = 'Key parameter is missing';
}
?>
You could try
var_dump( $_POST );
to see what's happening.
I suspect you have code like this:
<textarea>
</textarea>
when it should be like this (no spaces):
<textarea></textarea>

Numeric PHP validation?

I have some code written in php to validate a postcode field in my form. The code is meant to check that the field is not empty (mandatory) and matches one of 5 usable postcodes, if not it displays an alert. The problem i am having is that when i leave the field empty and hit the submit button the proper alert is show but if i enter a wrong value and hit submit the form just loads to a blank screen, can anyone spot a mistake in my code? :
<?php
if (isset($_POST['submit'])) {
$post = $_POST["post"];
$words = array('2747','2750','2753','2760','2777');
$msgp = "";
if (!empty($post)) {
foreach ($words as $item)
{
if (strpos($post, $item) !== false)
return true;
}
$msgp = '<span class="error"><b>Please enter correct postcode</b></span>';
return false;
} else if(empty($post)) {
$msgp = '<span class="error"><b>Please enter postcode</b></span>';
}
}
?>
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi">
<b>Post Code</b>
<br>
<input type="text" id="post" name="post" /><?php echo $msgp; ?>
</form>
return? Return where?
When you return in your main code, it's (nearly) the same as die()'ing.
So when you return, the remaining PHP won't be executed anymore.
I'd consider to set some variable like $success = true/false; instead of returning.
You return false after $msgp = '<span class="error"><b>Please enter correct postcode</b></span>'; therefor you do not continue to the form below... remove the returns from your code to be able to handle and show an error.
You are using return. Are you in a function() {} ? If so, all your variables are in function scope. You could do global $msgp; to make the variable accessible outside of the function.
If not... then you shouldn't use return.
Change php code to
<?php
if (isset($_POST['post'])) {
$post = intval($_POST["post"],0);
$words = array(2747,2750,2756,2760,2777);
$msgp = '<span class="error"><b>'.in_array($post,$words) ? "Please enter postcode" : "Please enter correct postcode" .'</b></span>';
}
There are a lot of things that can be simplified. For example codes as int array and using in_array() function. Return statement should be used to return something from method/function using it in global scope then execution of the current script file is ended. There is no need for it here. If there are more $words values you should consider using simple REGEX /[0-9]{4}/ and preg_match()
You want to display $msgp right? Use echo $msgp;. But you can return to nowhere in your code. (put it in a function).
Try this
<?php
$post = $_POST["post"];
$words = array('2747','2750','2753','2760','2777');
$msgp = "<span class='error'><b>Please enter correct postcode</b></span>";
function check($post){
global $words;
$return=true;
if (!empty($post)) {
foreach ($words as $item)
{
if (strpos($post, $item) !== false)
//$return=true;
}
} else if(empty($post)) {
$return=false;
}
return $result;
}
$return=check($post);
if($return === true){
// echo you are right!
}
else {
echo $msgp;
}

How do I check if any single element from an array is in a string?

I'm trying to create a function that searches through the user input to see if they have
entered the name of a day. For some reason, this function only seems to return true if any two day names have been entered. This could be something simple, but I can't seem to figure it out.
Here is my code:
<?php
if(isset($_POST['query']))
{
$query=$_POST['query'];
$dow=array('monday','tuesday','wednesday','thursday',
'friday','saturday','sunday');
foreach($dow as $day)
{
if(stripos($query, $day)==FALSE)
{
}
else
{
echo"hurray";
}
}
}
?>
<html>
<form action="datefunctiontester.php" method="post">
<p>Search</p><input type="text" name="query">
<input type="submit">
</form>
</html>
=== not == see the stripos manual entry
You should use
if (stripos($query, $day) === FALSE){
and not
if (stripos($query, $day)==FALSE){
This is because, if the name is found in the starting of the query, it will return '0' because the position of first character will be 0 which is false. To check if it exists use === which checks the type and not the value.
Also, you can use the in_array function instead of for loop.
if (isset($_POST['query']))
{
$query = $_POST['query'];
$dow = array('monday','tuesday','wednesday','thursday','friday','saturday','sunday');
if (in_array($query, $dow)
{
echo"hurray";
}
}
Try this:
if (isset($_POST['query']) {
$dow = array('monday','tuesday','wednesday','thursday','friday','saturday','sunday');
if (in_array(trim(strtolower($_POST['query'])), $dow) echo"hurray";
}
There's no need to use stripos() in this case.
// Force lower case for comparisons
$query = strtolower( $_POST['query'] );
$dow = array('monday','tuesday','wednesday','thursday',
'friday','saturday','sunday');
$found = in_array($query, $dow, true);
if($found)
{
// do something
}

Categories