full if then statement is not being read php - php

I have a program that evaluates an if then statement and returns true or false
false = everything is good
true = still need more info
so here is my code
function city_state_zip_requirement($parameters_ar){
//clear requirements if all the address fields are filled and the first and last or company is filled
if (!empty($parameters_ar['Address']) && !empty($parameters_ar['City']) && !empty($parameters_ar['State']) && !empty($parameters_ar['Zip']) && (!empty($paramenters_ar['First'] && !empty($paramenters_ar['Last'])) || !empty($paramenters_ar['Company']))){
return false;
// clear the requirement if the first and last name or company fields are filled and there is no filled field in the address city state or zip column
} elseif ((!empty($parameters_ar['First']) && !empty($parameters_ar['Last']) && empty($paramenters_ar['Address']) && empty($paramenters_ar['City']) && empty($paramenters_ar['State']) && empty($paramenters_ar['Zip'])) || (!empty($parameters_ar['Company']) && empty($paramenters_ar['Address']) && empty($paramenters_ar['City']) && empty($paramenters_ar['State']) && empty($paramenters_ar['Zip']))){
return false;
// clear the requirement if the email address field is filled and the adress fields are either all filled or all empty
} elseif (!empty($parameters_ar['Email_Address']) && empty($parameters_ar['Address']) && empty($parameters_ar['City']) && empty($parameters_ar['State']) && empty($parameters_ar['Zip'])){
return false;
} else {
return true;
}}
all the fields are pulled from a user form that sends data through $_POST
what I am trying to accomplish is if the user enters info into a first (first name) and last (last name) or company field the address fields must be either all filled or all empty (i.e. cannot have only state filled for example)
upon debugging the statement that is evaluating to be true (and therefore returning false) is the second from the top
the:
} elseif ((!empty($parameters_ar['First']) && !empty($parameters_ar['Last']) && empty($paramenters_ar['Address']) && empty($paramenters_ar['City']) && empty($paramenters_ar['State']) && empty($paramenters_ar['Zip'])) || (!empty($parameters_ar['Company']) && empty($paramenters_ar['Address']) && empty($paramenters_ar['City']) && empty($paramenters_ar['State']) && empty($paramenters_ar['Zip']))){
return false;
it doesnt seem to make sense that when a user inputs data into the form php is evaluating that the above statement is true (and therefore returning false) if only parameter_ar['First'] and $parameter_ar['Last'] or $paramenter_ar['Company'] is filled while one of the address fields is filled

Rewrite your code so that it only uses one return statement and make functions to validate your request param array based on the cases you want to evaluate. By breaking your code down into smaller pieces it will be more manageable. For example
function yourFunction($params) {
$needMoreInfo = true;
if (isValidCase1($params) || isValidCase2($params) ... ) {
$needMoreInfo = false;
}
return $needMoreInfo;
}
// define your validation functions here
Edit
The condition you find strange is
(
!empty($parameters_ar['First'])
&& !empty($parameters_ar['Last'])
&& empty($paramenters_ar['Address'])
&& empty($paramenters_ar['City'])
&& empty($paramenters_ar['State'])
&& empty($paramenters_ar['Zip'])
)
||
(
!empty($parameters_ar['Company'])
&& empty($paramenters_ar['Address'])
&& empty($paramenters_ar['City'])
&& empty($paramenters_ar['State'])
&& empty($paramenters_ar['Zip']))
)
Analysing the first part of the logical OR
Not empty: first name, last name
Empty: address, city, state, zip
This condition will evaluate to TRUE if first name and last name are the only fields filled out. Since a "return false" follows, in this case, FALSE is returned.
Read more about logical AND, OR, NOT if still unclear.
It could also be that there is an errore in the HTML form causing a submit different from what you expect bit this can't be determined with the code provided

I couldnt for the life of me figure out why PHP was ignoring the other && in the statements after $parameters_ar['First'] and $parameters_ar['Last'], as it turns out.
I was spelling parameters_ar['Address'] (and the other fields) incorrectly, I was instead spelling it paramenters_ar['Address'] once I fixed the spelling error the issues went away.
I am using Notepad++ and it seems I made the same mistake elsewhere in the file and so the autocomplete feature was bringing up what looked like what I was trying to type but was actually incorrect
This is why php was reading $paramenters_ar['Address'] as empty, because there was no value assigned to them and therefore evaluating to true and therefore returning false.
Thank You

Related

Check multiple conditions is empty php

I want to check the user has selected any one of the input field,
I 've tried like ,
if(empty($_POST["month"]) and ($_POST["eid"]))
{
...
}
But the condition is true when I'm using || opertator and the condition is false when I'm using &&.Why it is not working for && operator.How can I solve this?
Basically, a statement like:
if ($condition1 || $condition2) {}
returns TRUE when $condition1 OR $condition2 is true.
And, a statement like:
if ($condition1 && $condition2) {}
returns TRUE when both $condition1 AND $condition2 are true.
In your case, you need to use:
if(! empty($_POST["month"]) || ! empty($_POST["eid"])) {
// do something
}
I want to check the user has selected any one of the input field
Based on above statement, you can simply check for using isset():
if(isset($_POST["month"]) || isset($_POST["eid"]))
You can use this for checking empty field, while you use && the code is not working because ($_POST["eid"]) have no rules.
Example :
//You check the month are empty and the eid are ... ?
if(empty($_POST["month"]) && ($_POST["eid"]))
//Use this if you want to check the "month" and "eid" are Empty
if(empty($_POST["month"]) && empty($_POST["eid"])) {
... your validation here ...
}
//You can you is_null too
if(is_null($_POST["month"]) && is_null($_POST["eid"])) {
... your validation here ...
}
If you want to validate only one between $_POST["month"] or $_POST["eid"] just change the && to ||.
A compact way to do it is to make an array of all the values then check if they are empty.
If(empty(array($_POST["month"], $_POST["eid"]))){
// They are both empty
}else{
// Not empty
}
Another way of checking:
Has the user filled at least one of the fields is basically asking Are all the fields empty? If not - the user has checked at least one field, otherwise - none.
So simply use the && operator and add ! to the whole condition.
if(! ( empty($_POST['field1']) && empty($_POST['field2']) ... ) ) {
}
Edit:
OP's condition:
I've three set of filelds like date1 and date2 ,id and date, month If
user selects nothing from these three sets I want to display a message
if the user select any one of the sets they can go in.
I hope I have understood you right. If not, please share an example.
set 1 - date1 and date2
set 2 - id and date
set 3 - month
Code:
if( (empty($_POST['date1']) and empty($_POST['date2'])) or
(empty($_POST['id']) and empty($_POST['date'])) or
(empty($_POST['month'])) ){
echo 'your message here.';
} else {
//the user can go in.
}

If statement with && and multiple OR conditions in PHP

I'm having trouble trying to make the statement below work the way I want it to.
I am trying to display an error message for an order form if at least one text field is not filled out. Below is a snippet of my PHP code. The 'cookieGiftBox' is the name of a checkbox that users can select and if it is selected, they must enter an amount of cookies under their desired flavors in the text fields provided. How can I display an error message to display when the checkbox IS selected but NO text fields have been filled out?
<?php
if (isset($_POST['cookieGiftBox'])
&& (!isset($_POST['sugar'])
|| ($_POST['chocolateChip'])
|| ($_POST['chocolateChipPecan'])
|| ($_POST['whiteChocolateRaspberry'])
|| ($_POST['peanutChocolateChip'])
|| ($_POST['peanutButter'])
|| ($_POST['tripleChocolateChip'])
|| ($_POST['whiteChocolateChip'])
|| ($_POST['oatmealRaisin'])
|| ($_POST['cinnamonSpice'])
|| ($_POST['candyChocolateChip'])
|| ($_POST['butterscotchToffee'])
|| ($_POST['snickerdoodle']))) {
$error.="<br />Please enter an Amount for Cookie Flavors";
}
?>
&& takes precedence over ||, thus you would have to use parentheses to get the expected result:
if (isset($_POST['cookieGiftBox']) && (!isset($POST['sugar']) || ...)
Actually, to get check if nothing is selected, you would do something like this:
if checkbox is checked and not (sugar is checked or chocolatechip is checked) or the equivalent:
if checkbox is checked and sugar is not entered and chocolatechip is not entered....
If you want to know more, search for information about Boolean algebra.
Update: In your example and in the correct syntax the sentence I took as an example would like this (for the first sentence, note the not (!) and the parentheses around the fields, not the checkbox):
if (isset($_POST['cookieGiftBox']) &&
!(
isset($_POST['sugar']) ||
isset($_POST['chocolatechip'])
)
) { error ...}
Or the second sentence, which might be easier to understand (note the && instead of ||):
if (isset($_POST['cookieGiftBox']) &&
!isset($_POST['sugar']) &&
!isset($_POST['chocolatechip'])
) { error...}
Using ands makes sure it is only true (and thus showing the error) if none of the sugar, chocolatechips, etc. fields are set when the giftbox checkbox is checked.
So if the checkbox is checked, and no fields are set it looks like this:
(true && !false && !false) which is equivalent to (true && true && true) which is true, so it shows the error.
If the checkbox is checked and sugar is entered it would look like this:
(true && !true && !false), equ. to (true && false && true), equ. to false and thus no error is shown.
If both sugar and chocolatechip are entered also no error will be shown.
I have simillar issue:
I try use:
if (isset($this->context->controller->php_self) && ($this->context->controller->php_self != 'category') || ($this->context->controller->php_self != 'product') || ($this->context->controller->php_self != 'index')){ ... }
Thats didn't work, I change it to:
if (isset($this->context->controller->php_self) && ($this->context->controller->php_self != 'category') && ($this->context->controller->php_self != 'product') && ($this->context->controller->php_self != 'index')){ ... }
I dont know it is correct?
Edit. This is not correct, but for now i didnt know how to fix it.

Complicated `if`case, correct?

I'm trying really hard to figure out how to solve this problem. Please be gentle, i'm still learning!
There are four workplaces named: B.Avf, R.Avf, Office and Production. Products is passing theese workplaces. Now i'm building a script that can alert if the same product is passing the same workplace twice. Now, this is the hard part: If the product has passed "B.Avf" it can't pass "R.Avf" whitout an alert, same if the product has passed "R.Avf" it can't pass "B.Avf" whitout and alert. But if the product has passed for ex. "R.Avf" it´s ok to pass "Office" whitout an alert.
This is what i got so far: (It's like example number 5 =)
Maby should i create nested ifstatements instead?
This code will turn true all times!
PHP
if($_SESSION['user']['usr_workplace'] == "R.Avf" ||
$_SESSION['user']['usr_workplace'] == "B.Avf" &&
strpos($history, "R.Avf") !== FALSE ||
strpos($history, "B.Avf") !== FALSE)
Your if condition should be :
//IF this session user workplace is "B.Avf" or "R.Avf"
//AND "B.Avf" or "R.Avf" excist in history, then alert!
if(($_SESSION['user']['usr_workplace'] == "R.Avf" || $_SESSION['user']['usr_workplace'] == "B.Avf") && (strpos($history, "R.Avf") !== FALSE || strpos($history, "B.Avf") !== FALSE))
Your if statement can be made a lot simpler by removing one condition and still getting the desired result like so:
if(
($_SESSION['user']['usr_workplace'] == "R.Avf" || $_SESSION['user']['usr_workplace'] == "B.Avf")
&&
strpos($history, $_SESSION['user']['usr_workplace']) !== false
)
Notice how you don't need two strpos checks, as the first part of the if statement will only allow the second part to run if it was true.
It would be better to extract this to a method or simplify it further, but for what you've asked this will do :).
This works, it has the right braces:
if($_SESSION['user']['usr_workplace'] == "R.Avf" || ($_SESSION['user']['usr_workplace'] == "B.Avf" && (strpos($history, "R.Avf") !== FALSE || strpos($history, "B.Avf") !== FALSE)))
It checks for r.Avf first, OR and then checks all the conditions within the braces
you should break this if into 2 methods.
one should be called:
isUserSessionRBAvf($_SESSION['user']['usr_workplace'])
the other should check the strpos pos:
isHistoryAvf($history, "R.Avf")
and you would end up with just:
if(isUserSessionRBAvf(...) && isHistoryAvf(...))
this way you have a more readable code and easier to debug.
P.S. consider a different method naming
what you need to do is simply check with session value to $history so you will avoid checking two strpos() where you are doing static string checking:
here you are checking with static string:
strpos($history, "R.Avf") !== FALSE ||
strpos($history, "B.Avf") !== FALSE)
make it dynamic like this:
if($_SESSION['user']['usr_workplace'] == "R.Avf" || $_SESSION['user']['usr_workplace'] == "B.Avf" && strpos($history, $_SESSION['user']['usr_workplace']) !== FALSE )

PHP if status and !isset or !isset

I'm trying to match a condition where if the user status is 10 and ANY POST variables are not set it triggers an error:
if ($_SESSION['status']=='10' && !isset($_POST['a']) || !isset($_POST['B'])) {}
I can not use && conditions for any !isset as one variable may be set though another might not. I only want the condition to match if one or more variables are not set AND the status==10.
When testing if a $_POST variable !isset, I remove an input element from the page via a browser web tool (e.g. Firebug). When the form is submitted with the variable missing it's still passing validation incorrectly.
I am also seeking a PHP if grouping condition.
If you are looking for absolutely any PHP variables, I'd recommend this:
if (($_SESSION['status'] == 10) && (count($_POST) > 0)) {
You can then get the list of _POST var keys using array_keys($_POST).
If you are looking for a specific:
if (($_SESSION['status'] == 10) && (isset($_POST['A']) || isset($_POST['b']))) {
The order of the brackets is important. You can separate groups of logical statements with brackets.
Is that was what you were looking for?
$status = $_SESSION['status'];
if($status == '10'){
if(!isset($_POST['a']) or !isset($_POST['B'])){
//Triggers error.
}else{
//Another
}
}
Try making it a function:
function checkAllVars($dataVars, $requestVars) {
foreach($dataVars as $varname) {
if(!isset($requestVars[$varname])) {
return false;
}
}
return true;
}
$dataVars = array (
"varName1",
"varName2",
"varName3",
"varName4",
);
$allVarsSet = checkAllVars($dataVars, $_REQUEST);
you might be looking for
if($_SESSION['status']=='10' && (!isset($_POST['a']) || !isset($_POST['B']))){}
^ ^
which means if status = 10 and (if not set 'a' or not set 'B' or they can be both not set) do something
or you might be looking for
if(($_SESSION['status']=='10' && !isset($_POST['a'])) || ($_SESSION['status']=='10' && !isset($_POST['B']))){}

!is_null() not working as expected

dispatch_address_postcode
isn't mandatory and it will still run even if it's blank:
if (!is_null($_POST['personal_info_first_name']) &&
!is_null($_POST['personal_info_surname']) &&
!is_null($_POST['personal_info_email']) &&
!is_null($_POST['personal_info_telephone']) &&
!is_null($_POST['dispatch_address_country']) &&
!is_null($_POST['dispatch_address_first_name']) &&
!is_null($_POST['dispatch_address_surname']) &&
!is_null($_POST['dispatch_address_address']) &&
!is_null($_POST['dispatch_address_town']) &&
!is_null($_POST['dispatch_address_postcode']) &&
!is_null($_POST['dispatch_address_county']) &&
( ($_POST['payment_method'] == "Pay by credit card.") ||
(
($_POST['payment_method'] == "Pay by new credit card.") &&
!is_null($_POST['card_number']) &&
!is_null($_POST['expiration_date']) &&
!is_null($_POST['security_code'])
)
)
)
What gives?
"dispatch_address_postcode isn't mandatory and it will still run even if it's blank…"
Just look at that sentence again. If the field is not mandatory, it is perfectly okay if the code runs if the field is blank. If a field isn't mandatory, don't test it as mandatory.
The real problem is though, is_null only tests if the variable is null. POSTed values will never be null, if they're empty they will be '' (an empty string). All your !is_null tests will always be true, and you will get a warning if the variable isn't set (something you don't want to happen). The more appropriate test would be !empty.
Even more appropriate tests would include a test if the value appears to be valid (does email look like an email address, does telephone have at least x digits in it?). You should also loop through the fields to make your code more readable, endless nested and chained if conditions are no joy to look at.
$mandatoryFields = array('foo' => 'email', 'bar' => 'telephone');
foreach ($mandatoryFields as $field => $rule) {
if (empty($_POST[$field]) || !validateByRule($_POST[$field], $rule)) {
raiseHell();
}
}
It looks like you're trying to make sure all post variables are submitted. Would you like help with that?
Using !empty() may not be the answer to your specific question, but it would definitely help with what it looks like you're trying to do.
empty() returns TRUE if the $_POST key isn't set, if its an empty array, or even if its an empty string, so using !empty() is a good way to make sure that the user has filled in the information.
Try writing your own is_valid function and use that rather than is_null.
For example (and this is by no means comprehensive):
function is_valid(&$array, $key, $required=false) {
if(!array_key_exists($array))
return false;
$value = trim($array[$key]);
if(empty($value) && $required)
return false;
return true;
}
Use like so:
if(is_valid($_POST, 'personal_info_first_name', true) && ...)
!is_null($_POST['personal_info_first_name']) && !isset($_POST['personal_info_first_name'])
use array_key_exists('card_number', $_POST) && !empty($_POST['card_number'])
Edit: Please consider this before a downvote. I'm leaving this here to serve as a "what not to do". I would delete it because it's bad, but then nobody would learn from my mistakes.
DO NOT DO THIS - read the comments for great info on why this is bad
My answer is going to be wildly different, but I am a wildly different guy...
I JUST found that this will work. Instead of all that isset and things, just assign the variables programmatically! I think I have some refactoring to do... y'know on all my code...
if (!is_array($_POST)){exit "$_POST isn't an array";}
foreach ($_POST as $param => $value){
${$param} = secure($value);
}
//now you have a set of variables that are named exactly as the posted param
//for example, $_POST['personal_info_first_name'] == $personal_info_first_name
if ($payment_method == "Pay by credit card."){
//do stuff that you were gonna do anyways
} else if ($payment_method == "Pay by new credit card.") {
if ($card_number && $expiration_date && $security_code){
//do stuff that you were gonna do anyways
} else {
exit("info missing for credit card transaction");
}
} else {
exit("unknown payment method")
}
function secure($input){
//sanitize user input
}
If you use this code, then it doesn't matter what is null and what isn't within the foreach because anything that's null just won't be made. Then you can use nicer looking code (and probably faster code) to check for anything that is required.

Categories