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
Related
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';
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
}
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))
Why this condition passes even if I change the $_GET variable?
I've this code
elseif(isset($_GET['results']) && $_GET['results'] == 'reorder' &&
isset($_GET['sort_column']) && $_GET['sort_column'] != '' && isset($_GET['sort_order'])
&& $_GET['sort_order'] != '' && $_GET['sort_order'] == 'asc'
|| $_GET['sort_order'] == 'desc') { /*rest goes here*/ } else {redirect}
Link returns like this
http://localhost/system/results.php?script_id=2&results=reorder&sort_column=supplier_address&sort_order=desc
But when I change this sort_column=supplier_address to say for example sorcodsalumn=supplier_address it doesn't redirect, instead goes ahead, any idea why? But if I simply remove few letters and dont replace with something else it does redirect...
How come if am using this isset($_GET['sort_column'] and am modifying sort_column to something else still passes this condition
Basic PHP operator precedence... && evaluates before ||, so your entire statement boils down to:
(x && y && z && ....) || ($_GET['sort_order'] == 'desc')
You need to simplify that if(), add some () to enforce your own evaluation order, and then things should start working a bit better.
your AND's and OR's need to be bracketed properly.
else if (isset($_GET['results']) &&
$_GET['results'] == 'reorder' &&
isset($_GET['sort_column']) &&
$_GET['sort_column'] != '' &&
isset($_GET['sort_order']) &&
$_GET['sort_order'] != '' &&
($_GET['sort_order'] == 'asc' || $_GET['sort_order'] == 'desc'))
{
/*rest goes here*/
} else {
redirect
}
More specifically your last || needs its own brackets, as shown above.
You need to put a bracket around your || (OR) statement like this:
elseif(isset($_GET['results']) && $_GET['results'] == 'reorder' &&
isset($_GET['sort_column']) && $_GET['sort_column'] != '' && isset($_GET['sort_order'])
&& $_GET['sort_order'] != '' && ($_GET['sort_order'] == 'asc'
|| $_GET['sort_order'] == 'desc')) { /*rest goes here*/ } else {redirect}
Otherwise your statement will return true anytime sort_order is set to 'desc'.
I'm creating an edit page which should get called this way:
users.php?action=edit&id=5
This is my code for this:
} elseif (isset($_GET['action']) && $_GET['action'] == 'edit' && isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
As you see it's long. First a check with isset is needed. I know you can leave that out, but that way I'll get PHP notices when error reporting is set to 'E_ALL'.
I can create a function to make it shorter but that way I'll need to create too many functions as I have such code on different places in my scripts, each requiring different information.
Is there any way to make this code shorter?
Thanks!
Since action and id both are probably going to be used might as well set them at the top of the script:
$action = !empty($_GET['action'])?$_GET['action']:false;
$id = !empty($_GET['id'])?$_GET['id']:false;
switch ($action) {
case 'edit':
if ($id !== false) {
//processing here
}
break;
default:
echo 'No known action was passed through';
}
The initial variable declaration uses the ternary operator which is a shortened if/else as an fyi.
Extra Information
I prefer this method as appose to insane if/elseif/else statements, given that it is much easier to read and you do not have to think about your logic nearly as much, so it would make it less prone to errors.
You could write a function that takes an array of keys:
function check_get_params($keys) {
foreach ($keys as $key) {
if (! isset($_GET[$key]) ) {
return false;
}
}
return true;
}
Then your line above would be:
} elseif (check_get_params(array('action', 'id')) && $_GET['action'] == 'edit' && is_numeric($_GET['id'])) {
which would be cleaner as:
} elseif (check_get_params(array('action', 'id'))) {
if ($_GET['action'] == 'edit' && is_numeric($_GET['id'])) {
I would check parameters first:
$action = (isset($_GET['action']) && !empty($_GET['action'])) ? $_GET['action'] : false;
$id = (isset($_GET['id']) && !empty($_GET['id'])) ? $_GET['id'] : false;
settype($id, 'int'); // "123" became 123(int)
And then go with:
} elseif ($action && $id && $action == 'edit' && $id > 0) {
// here we are
}