Check multiple conditions is empty php - 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.
}

Related

full if then statement is not being read 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

PHP If a variable equals this or this

I have this if statement in my PHP:
if($_SESSION['usrName']!='test1'){
header('location:login.php');
}
But i want it to be something like this:
if($_SESSION['usrName']!='test1' or 'user'){
header('location:login.php');
}
But i cant figure out how to do it in PHP code. I have tried this:
if($_SESSION['usrName']!='test1','user'){
header('location:login.php');
}
And this:
if(($_SESSION['usrName']!='test1')||($_SESSION['usrName']!='user')){
header('location:login.php');
}
Can anybody help please?
You have to replace the || with &&. Because you only want to redirect when both conditions are true.
if(($_SESSION['usrName']!='test1') && ($_SESSION['usrName']!='user')){
header('location:login.php');
}
if (!in_array($_SESSION['usrName'], array('test1', 'user')) {
header('location:login.php');
}
This checks if variable $_SESSION['usrName'] is not in list of strings to simplify additional allowed user.
As others have said, you need to be careful with your boolean logic - (NOT X) || (NOT Y) is equivalent to NOT (X AND Y), whereas what you want is NOT (X OR Y) which is equivalent to (NOT X) AND (NOT Y).
For this particular situation, there are also a couple of other options, although none as neat as the invalid syntaxes you tried.
First, there is in_array(), which is easy to read, but not very efficient if you use it a lot with long lists (for a simple case like this, it's not worth worrying about performance, though):
$allowed_users = array('test1', 'user');
if ( ! in_array($_SESSION['usrName'], $allowed_users ) { ... }
Or, you can build a hash with the usernames as keys; this is more efficient as the list grows, because PHP can check for a key without looping through the whole list:
$allowed_users = array('test1' => true, 'user' => true);
if ( ! array_key_exists($_SESSION['usrName'], $allowed_users) ) { ... }
// Or, if you don't mind PHP raising a few notices about accessing undefined keys
if ( ! $allowed_user[ $_SESSION['usrName'] ] ) { ... }
Finally, you can use a switch statement, with the labels falling through, and a default case acting as the "else":
switch ( $_SESSION['usrName'] )
{
case 'test1':
case 'user':
// These users are allowed :)
break;
default:
header('location:login.php');
}
Which, if any, of these you choose to use will depend on how you expect the code to grow in future, but they're useful tricks to know.
Your last attempt is almost correct.
However...
if (var != something || var != something-else)
...will always be true, because one of those conditions will always match. Even if it's equal to one side, it won't be equal to the other.
When you're testing two negatives like that, you need to use AND (&&) instead of OR (||).
if (($_SESSION['usrName']!='test1') && ($_SESSION['usrName']!='user'))
This will match if it's not equal to one, and also not equal to the other.
Currently, you're checking if either one of conditions are true. The last condition will evaluate to true if either one of the conditions are correct. I assume you're trying to check if both the the conditions are true. In that case, you'll need && instead of ||.
Try:
if( ($_SESSION['usrName'] != 'test1') && ($_SESSION['usrName'] != 'user') ) {
header('location:login.php');
}
You need to do something like:
if($_SESSION['usrName'] != 'test1' and $_SESSION['usrName'] != 'user'){
header('location:login.php');
}
The first attempt of yours is equivalent to:
if(($_SESSION['usrName']!='test1') or 'user'){
header('location:login.php');
}
Second seems like invalid syntax
Third is almost right, you just need to replace || with and or &&, as anything will be unequal to either 'user' or 'test1'

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']))){}

PHP operators if statement 'and' and 'or'

I have an if statement that I want to control with having one field needing input and they have to pick one of the other 2 choices.
if(test1 && test || test3){
//Something here
}
Should I do it like this:
if(test1 && (test2 || test3)){
//do stuff
}
How would I go about doing this. I can't wrap my head around the logic...
if ($requiredField && ($optional1 || $optional2)) {
/* Do something */
}
For the /* Do something */ bit of code to be executed, the if statement has to evaluate to TRUE.
This means, that $requiredField must be TRUE, and so must be ($optional1 || $optional2).
For $requiredField to be TRUE, it just needs to be filled in - and for the second part: ($optional1 || $optional2) either optional1 or optional2 would do it.
Edit:
After rereading the question, it seems that I might have misunderstood you. If the user must enter one specific piece of information, and must choose only one (not both) out of two options - then the following should be used.
if ($requiredField && ($optional1 ^ $optional2)) {
/* Do something */
}
This means that $optional1 or $optional2 must be filled out - but not both of them.
From the sound of it, you want the latter:
if ($test1 && ($test2 || $test3)){
//do stuff
}
Think of it as two conditions needing to be met. This gives you those two conditions. The second condition just happens to be another condition. The first option you posted, however, is quite the opposite as it can allow execution if just $test3 is true
test1 && (test2 || test3) is very easy to understand from the first place - Choose test1 && (test2 || test3) means one the last two. Very clear.
test1 && test || test3 - doesn't seem to be correct:
test1 = false
test2 = false
test3 = true
false && false || true = true
doesn't actually fit your criteria.
... they have to pick one of the other 2 choices
I'm just throwing a guess out here. If you really want to ensure that one, but only one of the two other options are selected, then you need xor:
if ($required AND ($and_either XOR $or_other)) {
You can have 'nested' if statements withing a single if statement, with additional parenthesis.
if(test1 && (test2 || test3)){
//do stuff
}
Your logic is right but your sintax isnt, you should compare the values of the variables as show, or simply ignore them as saying you are trying to compare them as they are TRUE.
$test1=true;
$test2=true;
$test3=false;
if($test1==true && ($test2==true || $test3==true){ echo "YES";}
This will output YES.

!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