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().
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
On my website I have plenty of form and fields, I have a system that works perfectly but is really painful and to get up and running.
This is what my system does, once you send the form all the info is sent to a class which possesses all the data and validates it. It also stores the value of the field like this $_SESSION['userUpdate']['firstName'][1] = $firstName;
If there is an error it creates a session variable like this $_SESSION['userUpdate']['firstName'][0] = 1; the 1 tells that the field was empty. If there is no error the session variable would be at 0.
If no errors where found in the validation process the data is sent to the database.
After that the form page is reloaded with :
header( 'HTTP/1.1 303 See Other' );
header( 'Location: '.curPageURL().'' );
I use that so that you cannot resend the data when reloading the page. That is the reason I'm using all these session variables.
Then with a lot of it/else if/else I check the values of the session variables and output errors and also populate the form with the data entered previously.
Let me show you an example for a firstname field.
This is the HTML code :
<label for="firstName" class="block">First Name</label>
<span>Your first name goes here.</span><?php echo $text_first_name ?>
<input type="text" id="firstName" class="mediaText" name="firstName" value="<?php echo $first_name2; ?>" onchange="needToConfirm=true" <?php echo $style_first_name ?> />
This is the validation process by the class :
$_SESSION['ui']['first_name'][1] = $this->first_name;
if (isset($this->first_name))
{
if($this->first_name == NULL)
{
$_SESSION['ui']['first_name'][0] = 1;
}
else if(minRange(3, $this->first_name))
{
$_SESSION['ui']['first_name'][0] = 2;
}
else
{
array_push($set, "FirstName = '".$db->sql_escape($this->first_name)."'");
}
}
This is the php code that handles the eventual errors :
$error_bg = "style=\"background:#EE5C42\"";
//FIRST NAME
if($_SESSION['ui']['first_name'][0] == 1)
{
$style_first_name = $error_bg;
$first_name2 = $_SESSION['ui']['first_name'][1];
}
else if($_SESSION['ui']['first_name'][0] == 2)
{
$style_first_name = $error_bg;
$first_name2 = $_SESSION['ui']['first_name'][1];
$text_first_name = "<span class=\"errorText\">Your first name must consist of at least 3 characters.</span>";
}
else
{
$first_name2 = $userdetails["FirstName"];
}
At the end of the page there is a little function to unset the session variables.
I am wondering it there is any way to make this simpler and easier to get up and running ?
If you're asking for code optimization advice, here's how I would do that:
// so you have bunch of error codes
$possible_errors = array(
'0' => '', // No error
'1' => '', // Error, but no error message
'2' => 'Your %s must consists of at least 3 characters',
...
);
// then you have form fields stored in session
// fields in session should be named like the keys in $userdetails
// 'formName' => array('FirstName' => array(0, 'German'), 'LastName' => array('1', ''))
$errors = $values = array();
foreach ($_SESSION['formName'] as $field => $element) {
if ($element[0] > 0) { // Has error
$error_code = $element[0];
$error_message = $possible_errors[$error_code];
if (!empty($error_message)) {
$errors[$field] = sprintf($error_message, $field);
}
} else {
$values[$field] = $userdetails[$field];
}
}
// in here you end up with two arrays:
// - $errors Error messages keyed by field name
// - $values Values keyed by field name
// You use them like this
<label for="firstName" class="block">First Name</label>
<span>Your first name goes here.</span><?php if (array_key_exists('FirstName', $errors)) echo $errors['FirstName']; ?>
<input type="text" id="firstName" class="mediaText" name="firstName"
value="<?php echo $values['FirstName']; ?>"
onchange="needToConfirm=true"
<?php if(array_key_exists('FirstName', $errors)):?>style="background:#EE5C42"<?php endif;?> />
I'd recommend adding in some client side validation using the very good Bassistance jQuery Validate plugin.
I have a form that contains a number of textboxes i.e. Volome, Gain, Treble, Middle and Bass. Only whole numbers can be entered, which is validated with javascript and the Maxlength is set to, so no problem there. But how do I make sure that only numbers between 0 and 65535 are entered.
<?php
$name = $_POST['ampMod'];
$volume = 'Volume = '. $_POST['volume'];
$gain = 'Gain = '. $_POST['gain'];
$treble = 'Treble = '. $_POST['treble'];
$middle = 'Middle = '. $_POST['middle'];
$bass = 'Bass = '. $_POST['bass'];
if($volume != null && $gain != null && $treble != null && $middle != null && $bass != null)
{
echo "<h3> $name </h3>";
echo "<table><tr>";
echo "<td>$volume</td>";
echo "<td>$gain</td>";
echo "<td>$treble</td>";
echo "<td>$middle</td>";
echo "<td>$bass</td>";
}
else
{echo ("Please try again. Values must be between 0-65535. 0=Off 65535=Full On 10<br>Click here to try again!");}
?>
It is important to mention that your $volume, $gain, $treble, $middle and $bass will never actually be null as you have assigned a string to them in addition to the $_POST value. In addition you should always check if the $_POST values exist before trying to use them (or you will get an undefined notice message).
Here is an example for a PHP version based on the code you had (untested, but should work fine).
<?php
function isValidRange( $value, $low = 0, $high = 65535) {
// validate / cast value as int (add additional validation here
$value = (int)$value;
if ( $value > $high || $value < $low ) {
// return null (not a valid value)
return null;
}
// otherwise the value is valid so return it
return $value;
}
// make sure the $name var is safe to use
$name = ( isset($_POST['ampMod']) ) ? htmlentities($_POST['ampMod'],ENT_QUOTES,'UTF-8') : null;
$volume = ( isset($_POST['volume']) ) ? isValidRange($_POST['volume']) : null;
$gain = ( isset($_POST['gain']) ) ? isValidRange($_POST['gain']) : null;
$treble = ( isset($_POST['treble']) ) ? isValidRange($_POST['treble']) : null;
$middle = ( isset($_POST['middle']) ) ? isValidRange($_POST['middle']) : null;
$bass = ( isset($_POST['bass']) ) ? isValidRange($_POST['bass']) : null;
if( isset($volume) && isset($gain) && isset($treble) && isset($middle) && isset($bass) )
{
echo "<h3> $name </h3>";
echo "<table><tr>";
echo "<td>Volume = $volume</td>";
echo "<td>Gain = $gain</td>";
echo "<td>Treble = $treble</td>";
echo "<td>Middle = $middle</td>";
echo "<td>Bass = $bass</td>";
echo "</tr></table>";
} else {
echo ("Please try again. Values must be between 0-65535. 0=Off 65535=Full On 10<br>Click here to try again!");}
?>
Lastly I would not recommend just relying on JavaScript to actually check if your values are safe to use (i.e. echo them out), but using js as a pre-warning to users and then properly validating with PHP is the best way to go.
Just do something like this? Don't know why you would want to go between 0 and 65535. I doubt you want them to go that high. If you do just change 10 to 65535
if($value > 10 || $value < 0)
{
echo "Value cant be higher then 10 or lower then 0";
}
This makes sure the value is between 10 and 0
In situations like this, I often prefer to silently clean the form input. You've got client-side validation in place already. If the value is higher than allowed, just set the value to the maximum allowed instead of showing an error message.
// Clean the posted data and prevent notices if not set
$volume = (isset($_POST['volume'])) ? (int) $_POST['volume'] : 0;
// Make sure the value is within a certain range
$min = 0;
$max = 10;
$volume = min($max, max($min, $volume));
You can make use of the filter extension (bundled by default since 5.2):
$FILTER_VALIDATE_KNOB = array(
'filter' => FILTER_VALIDATE_INT,
'options' => array(
'min_range' => 0,
'max_range' => 65535,
)
);
$res = filter_input_array(INPUT_POST, array(
'ampMod' => $FILTER_VALIDATE_KNOB,
'volume' => $FILTER_VALIDATE_KNOB,
'gain' => $FILTER_VALIDATE_KNOB,
'treble' => $FILTER_VALIDATE_KNOB,
'middle' => $FILTER_VALIDATE_KNOB,
'bass' => $FILTER_VALIDATE_KNOB,
));
if (is_null($res) || in_array(null, $res, true)) {
// some or all fields are missing
// - missing fields have null value
} elseif (in_array(false, $res, true)) {
// some or all fields have a wrong value
// - wrong values have false value
}
I would do it with javascript. That way, you wouldn't have to submit the form and if the user types a higher number the alert (or something nicer) is shown:
In the input field, just call the javascript function:
<input id="thefirstnumbervalue" type="text" onchange="checknumber('thefirstnumbervalue')" />
<input id="thesecondnumbervalue" type="text" onchange="checknumber('thesecondnumbervalue')" />
In the function:
function checknumber(theid){
var mynumbervalue = document.getElementById(theid).value;
if (mynumbervalue > 65535){
document.getElementById(theid).value = "65535";
alert("Please try again. Values must be between 0-65535. ...");
}
if(mynumbervalue < 0){
document.getElementById(theid).value = "0";
alert("Please try again. Values must be between 0-65535 ...");
}
}
This is a simple approach in raw javascript. If you use ajax and jquery the result could be easier and nicer. This is complementary to the php solution, as you should also check the data before inserting in your database.
I'm using an old random() function for creating a validation code for an AJAX commenting system I found on the web (source code at LINK ).
The idea behind is pretty simple:
function Random()
{
$chars = "ABCDEFGHJKLMNPQRSTUVWZYZ23456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 4)
{
$num = rand() % 32;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
$random_code = Random();
and then in the form, just before the SUBMIT button:
<label for="security_code">Enter this captcha code: <b><? echo $random_code; ?></b></label>
<input type="text" name="security_code" id="security_code" />
<input name="randomness" type="hidden" id="randomness" value="<?php $random_code; ?>">
My AJAX commenting system uses something like this for checking if a field is blank (ie. if there are any errors):
$errors = array();
$data= array();
[...]
if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['name'] = 'Please enter a name.';
}
if(!empty($errors)){
[...]
}
so I wrote this:
if(!($data['security_code'] = filter_input(INPUT_POST,'security_code',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
{
$errors['security_code'] = 'You did not enter the validation code.';
}
elseif(!($data['security_code'] = $randomness))
{
$errors['security_code'] = 'You entered the validation code incorrectly. Please note that it is case sensitive.';
}
However when I click on the SUBMIT button after having inserted a random text in the validation code textfield ( test it by yourself at LINK ) I always get the "You entered the validation code incorrectly." message.
print_r($_POST) gives an empty array and then the script hangs after I click on submit:
Array
(
)
What am I missing? The original captcha code gets lost at some point in the validation process (the 3rd and 4th blocks of code).
Thanks in advance
After seeing your code here, I see that the static function validate doesn't know the variable $randomness! From your submit.php, you are making the following call:
$arr = array();
$validates = Comment::validate($arr);
The function validate doesn't know anything about the variable $randomness unless you pass such a thing to it - it is in a different scope.
Try modifying the above mentioned code as such:
$arr = array(); // no change here
$randomness = isset($_POST['randomness']) ? $_POST['randomness'] : '';
// Check for empty randomness before you validate it in Comment::validate
// so that you donot verify for '' == '' there.
$validates = Comment::validate($arr, $randomness);
And alter the validate function as follows:
public static function validate(&$arr, $randomness)
{
I know its not the elegant solution - that would require few more things that you'd learn well for yourself, this is just to show you the way...
Let me know how it goes.
instead of:
<input name="randomness" type="hidden" id="randomness" value="<?php $random_code; ?>">
write:
<input name="randomness" type="hidden" id="randomness" value="<?php echo $random_code; ?>">
also instead of:
elseif(!($data['security_code'] = $randomness))
{
$errors['security_code'] = 'You entered the validation code incorrectly. Please note that it is case sensitive.';
}
maybe this:
elseif($data['security_code'] != $randomness) {
$errors['security_code'] = 'You entered the validation code incorrectly. Please note that it is case sensitive.';
}
also, from where $data get its values? $_POST, $_GET?
print_r() it and also the $_REQUEST to light up.