Checking Multiple $_GET variables if equals a string - php

if(isset($_GET['a']) || isset($_GET['b']) || isset($_GET['c'])){
if(($_GET['a'] || $_GET['b'] || $_GET['c']) == "x"){
echo "YES";
} else {
echo "NO";
}
}
in this php code, i'm trying to check if one of those requests isset and if one of them value == 'x' or not, But the 2nd part if(($_GET['a'] || $_GET['b'] || $_GET['c']) == "x") doesn't work as intended at all, I wrapped it inside () hoping it would work, In this condition, do i have to separate it as i did inthe isset() part? or is there a better method to do that?

This is likely what you are looking for
UPDATE - I just changed || to && for the last condition in case you were quick to try it out.
if( (isset($_GET['a']) && $_GET['a'] == "x") || (isset($_GET['b']) && $_GET['b'] == "x") || (isset($_GET['c']) && $_GET['c'] == "x")){
echo "YES";
} else {
echo "NO";
}

If you have to write a lot of conditionals you could use one of the following:
Using a foreach and a conditional:
$either_abc_is_x = function() {
$keys = ['a','b','c'];
foreach($keys as $key)
if(isset($_GET[$key]) && $_GET[$key] == "x")
return true;
return false;
};
echo $either_abc_is_x() ? 'YES' : 'NO';
Using a an array filter with a conditional:
$get_abc_keys_equal_to_x = array_filter(['a','b','c'], function($v) {
return isset($_GET[$v]) && $_GET[$v] == 'x';
});
echo $get_abc_keys_equal_to_x ? 'YES' : 'NO';
Array gymnastics:
$either_abc_is_x = isset($_GET) && in_array('x', array_intersect_key($_GET, array_flip(['a','b','c'])));
echo $either_abc_is_x ? 'YES' : 'NO';

Related

If either of two cookies exist do something, in PHP

I know that || or && need to be used but I can't work out the correct or best way to format this.
My code for one cookie:
if(isset($_COOKIE['mycookie'])) {
if($_COOKIE['mycookie']=="value1") {
// do some stuff
}
}
But I'd like to include another cookie in this routine where either one can be true for the "stuff" to work.
I'm just not sure how to format this. Is it something like this?
if(isset($_COOKIE['mycookie'] || ['mycookie2')) {
if($_COOKIE['mycookie']=="value1" || $COOKIE['mycookie2']=="value2") {
// do some stuff
}
}
You can write all in one if statement if you want like this:
(The OR statement in the isset() function is not going to work)
if ( (isset($_COOKIE['mycookie']) && $_COOKIE['mycookie'] == "value1") || (isset($_COOKIE['mycookie2']) && $_COOKIE['mycookie2'] == "value2") )
You need to do the || outside the function, to combine the results of all the calls.
if (isset($_COOKIE['mycookie']) || isset($_COOKIE['mycookie2'])) {
// do some stuff
}
It will be:
if (isset($_COOKIE['mycookie']) || isset($_COOKIE['mycookie2'])) {
if ($_COOKIE['mycookie'] == "value1" || $_COOKIE['mycookie2'] == "value2") {
// do some stuff
}
}
Or even:
if ((isset($_COOKIE['mycookie']) || isset($_COOKIE['mycookie2') && ($_COOKIE['mycookie'] == "value1" || $_COOKIE['mycookie2'] == "value2")) {
// do some stuff
}
to avoid nested if.
Try this
if((isset($_COOKIE['mycookie']) && $_COOKIE['mycookie']=="value1")
|| 9isset($_COOKIE['mycookie2']) && $_COOKIE['mycookie2'] =="value2" )) {
// do some stuff
}
Try this. It puts all requirements in one if statement:
if( (isset($_COOKIE['mycookie'] && $_COOKIE['mycookie']=="value1") || (isset($_COOKIE['mycookie2']) && $_COOKIE['mycookie2']=="value2") ) {
// do some stuff
}
You can use one if condition instead of nested if. If you required to validate both then
if(isset($_COOKIE['mycookie'], $_COOKIE['mycookie2']) && ($_COOKIE['mycookie'] == "value1" && $_COOKIE['mycookie2']=="value2")) {
// do some stuff
}
Or if you have to validate one of them then
if((isset($_COOKIE['mycookie']) && $_COOKIE['mycookie']=="value1") || (isset($_COOKIE['mycookie2']) && $_COOKIE['mycookie2'] == "value2") ) {
// do some stuff
}

Please help! How to express the cases in if clause?

I have string $a,$b,$c
I know if all of them not null express in this way:
if($a!="" && $b!="" && $c!="")
But if either 2 of them not null then go into the true caluse
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(either 2 are not null){
**do another things here**
}
How to express it?
I would write a simple function like this to check:
function checkInput($var)
{
$nulls=0;
foreach($var as $val)
{
if(empty($val))
{
$nulls++;
}
}
return $nulls;
}
Then access it like this:
$inputs=array($a, $b, $c.... $z);
$nullCount=checkInput($inputs);
if($nullCount==0)
{
// All nulls
}
if($nullCount>2)
{
// More than 2 nulls
}
or for an one-off test, just pop the function into the actual if statement like this:
if(checkInput($inputs)>2)
{
// More than 2 nulls...
}
etc etc. You can then use the one function to check for any number of nulls in any number of variables without doing much work - not to mention change it without having to rewrite a long if statement if you want to modify it.
Other answers are good, but you can expand this to easily handle more variables:
$variables = array($a, $b, $c, $d, ....);
$howManyNulls = 0;
foreach($variables as $v){
if($v == ''){
$howManyNulls++;
}
}
if($howManyNulls == count($variables) - 2){
// do stuff
}
you can try this
if($a!="" && $b!="" && $c!="")
{
** do the things here **
}
else if(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!=""))
{
**do another things here**
}
Try:
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(($a!="" && $b!="") || ($a!="" && $c!="") || ($b!="" && $c!="")){
**do another things here**
}
$var[] = empty($a) ? 0:$a;
$var[] = empty($b) ? 0:$b;
$var[] = empty($c) ? 0:$c;
$varm = array_count_values($var);
if ($varm[0] === 0) {
//Code for when all aren't empty!
} elseif ($varm[0] === 1) {
//Code for when two aren't empty!
}
N.B; You may need to replace the 0 for a string/integer that will never crop up, if your variables are always strings or empty then 0 will do for this. The method for using bools within this would require more code.
$nullCount = 0
if($a!=""){ ++$nullCount; }
if($b!=""){ ++$nullCount; }
if($c!=""){ ++$nullCount; }
if($nullCount == 3){ // all are null
// do smth
}else if($nullCount == 2){ // only two are null
// do other
}
Just for fun, here's something potentially maintainable, should the list of arguments increase:
function countGoodValues(...$values) {
$count = 0;
foreach($values as $value) {
if($value != "") {
++$count;
}
}
return $count;
}
$goodValues = countGoodValues($a, $b, $c); // Or more... or less
if($goodValues == 3) {
// Do something here
}
else if($goodValues == 2) {
// And something else
}
Reference for the ... construct (examples #7 and #8 in particular) are available on php.net.
You can use double typecasting (to boolean, then to number) in conjunction with summing:
$count = (bool)$a + (bool)$b + (bool)$c;
if ($count == 3)
// ** do the things here **
else if ($count == 2)
//**do another things here**
There is also possible such solution:
<?php
$a= 'd';
$b = 'a';
$c = '';
$arr = array( (int) ($a!=""), (int) ($b!=""), (int) ($c!=""));
$occ = array_count_values($arr);
if ($occ[1] == 3) {
echo "first";
}
else if($occ[1] == 2) {
echo "second";
}
If you have 3 variables as in your example you can probably use simple comparisons, but if you have 4 or more variables you would get too big condition that couldn't be read.
if (($a!="") + ($b!="") + ($c!="") == 2) {
// two of the variables are not empty
}
The expression a!="" should return true (which is 1 as an integer) when the string is not empty. When you sum whether each of the strings meets this condition, you get the number of non-empty strings.
if (count(array_filter([$a, $b, $c])) >= 2) ...
This is true if at least two of the variables are truthy. That means $var == true is true, which may be slightly different than $var != "". If you require != "", write it as test:
if (count(array_filter([$a, $b, $c], function ($var) { return $var != ""; })) >= 2) ...
if($a!="" && $b!="" && $c!="") {
echo "All notnull";
} elseif(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!="")) {
echo "Either 2 notnull";
}

Database Sanitize Check owner

This is code for Delete link:
<a href="picture_manager.php?do=delete&id=<?php print $picturedata['id']; ?>" >Delete</a>
This is my current database syntax:
if (array_key_exists('do', $_GET) && $_GET['do'] == "delete" && array_key_exists('id', $_GET))
{
$pictureid = trim(sanitize($_GET['id']));
if ($picture->delete($pictureid) === true)
{
header('Location: picture_manager.php?success=removed');
}
}
With code above, other user can delete others user picture like = picture_manager.php?do=delete&id=(victim).
Now I found solution to prevent abuse by other user, I change the old syntax as below:
This is my new database syntax:
if (!array_key_exists('id', $_GET) || $_GET['id'] == "" || $picture->pictureExists(trim(sanitize($_GET['id']))) === false || $picture->checkOwn($user->getUserID(trim(sanitize($_SESSION['key']))), trim(sanitize($_GET['id']))) === false)
{
header('Location: picture_manager.php');
}
else
{
$pictureid = trim(sanitize($_GET['id']));
if ($picture->delete($pictureid) === true)
{
header('Location: picture_manager.php?success=removed');
}
}
Sadly, it did not work "The page isn't redirecting properly - said firefox browser"
Looking for expert right now.
I found solution in below answer.
NOW EDIT:
Its difficult to me when I coded as below:
if (isset($_GET['do']) && $_GET['do'] == 'delete' && (!array_key_exists('id', $_GET) || $_GET['id'] == "" || $picture->pictureExists(trim(sanitize($_GET['id']))) === false || $picture->checkOwn($user->getUserID(trim(sanitize($_SESSION['key']))), trim(sanitize($_GET['id']))) === false))
{
header('Location: picture_manager.php');
}
else
{
$pictureid = trim(sanitize($_GET['id']));
if ($picture->delete($pictureid) === true)
{
header('Location: picture_manager.php?success=removed');
}
}
The file doesn't delete when I click i.e picture_manager.php?do=delete&id=6125
Whats wrong with my code?
infinite redirect, !array_key_exists('id', $_GET) will proceed always. you need add ?do=delete to validation, like
<?php if (isset($_GET['do']) && $_GET['do'] == 'delete' && (!array_key_exists('id', $_GET) || $_GET['id'] == "" || $picture->pictureExists(trim(sanitize($_GET['id']))) === false || $picture->checkOwn($user->getUserID(trim(sanitize($_SESSION['key']))), trim(sanitize($_GET['id']))) === false))

Shortest way to code this php multiple if condition

I am trying to do a query like:
If $_GET['page'] == 'items' AND $_GET['action'] == 'new' OR 'edit'
Here's what I have:
if (isset($_GET['page']) && $_GET['page'] == 'items') {
if (isset($_GET['action']) && $_GET['action'] == 'new' || isset($_GET['action']) && $_GET['action'] == 'edit') {
// This is what Im looking for
}
}
Is this correct, and is this the easiest way to make this query?
You could have done it like this as well:
if (isset($_GET['page']) && $_GET['page'] == 'items') {
if (isset($_GET['action']) && ($_GET['action'] == 'new' || $_GET['action'] == 'edit')) {
}
}
Your way is perfectly fine, although I would almost be tempted to do it the following way. The only reason I suggest this is that your code requires that both action and page are set. If action is not set then there isn't much point checking if the page is == 'items'.
if(isset($_GET['page']) && isset($_GET['action'])) {
if($_GET['page'] == 'items' && ($_GET['action'] == 'new' || $_GET['action'] == 'edit')) {
//do code here
}
}
You may also try in_array like:
if (isset($_GET['page']) && $_GET['page'] == 'items')
{
if ( !empty( $_GET['action'] ) && in_array( $_GET['action'], array( 'new', 'edit' ) )
{
// This is what Im looking for
}
}
That is one of possible solutions
if ( #$_GET['page'] == 'items' && in_array(#$_GET['action'], array('new','edit')))
Everything is ok, but also you can use function:
function paramIs($param, $values) {
$result = false;
foreach ((array)$values as $value) {
$result = $result || isset($_GET[$param]) && $_GET[$param] == $value;
}
return $result;
}
Usage:
if (paramIs('page', 'items') && paramIs('action', array('new', 'edit')))
{
// your code here
}
It will reduce the number of repetitions in your code and encapsulate logic in one place

Simple PHP Condition help: if($Var1 = in list($List) and $Cond2) - Is this posslbe?

Is this a possible function?
I need to check if a variable is existent in a list of ones I need to check against and also that cond2 is true
eg
if($row['name'] == ("1" || "2" || "3") && $Cond2){
doThis();
}
It's not working for me and all I changed in the copy paste was my list and the variable names
if(in_array($row['name'], array('1', '2', '3')) && $Cond2) {
doThis();
}
PHP's in_array() docs: http://us.php.net/manual/en/function.in-array.php
You're lookin for the function in_array().
if (in_array($row['name'], array(1, 2, 3)) && $cond2) {
#...
if (in_array($name , array( 'Alice' , 'Bob' , 'Charlie')) && $condition2 ) {
/* */
}
use in_array function
if(in_array($row['name'], array(1,2,3)) && $cond2){
do ...
}
$name = $row['name'];
if (($name == "1" || $name == "2" || $name == "3") && $cond2)
{
doThis();
}
I have something simpler than that, if it's still possible...
if(strpos("1,2,3", $row['name']) !== false) && $Cond2) {
doThis();
}

Categories