PHP if condition with and and or - php

I have this condition here:
if($_SERVER['REQUEST_URI'] != '/page.php' || ($_SERVER['REQUEST_URI'] != '/' && $_SERVER['REQUEST_URI'] != '/index.php')){
//do something, but not on index or page . php
}
it works on the index page, but not page.php...what am i doing wrong?

You can do it easier...
if( ! in_array( $_SERVER['REQUEST_URI'], array("/page.php", "/", "/index.php") ) ) {
// do something...
}

You have logical error use
if(!($_SERVER['REQUEST_URI'] == '/page.php' || $_SERVER['REQUEST_URI'] == '/' || $_SERVER['REQUEST_URI'] == '/index.php')){
//do something, but not on index or page . php
}
or better
if(!in_array($_SERVER['REQUEST_URI'], ["/page.php", "/", "/index.php"])){
//do something, but not on index or page . php
}

Related

How do I check for 2 keywords in PHP

I want to check for my session. The code below works:
if ($_SESSION["rol"] != 'trainer') {
}
But this code doesnt work:
if ($_SESSION["rol"] != 'trainer' || 'commandant') {
}
It should check for both, because both have permission. What am I doing wrong?
Use this
if ($_SESSION["rol"] != 'trainer' || $_SESSION["rol"] != 'commandant') {
}
$role = ['trainer','commandant'];
if(!in_array($_SESSION['rol'],$role))
{
//do some stuff
}
I will probably do the following, where the isset ensures the key exists (and helps reduce warnings when the key is not available):
if (isset($_SESSION["rol"]) && ($_SESSION["rol"] != 'trainer' || $_SESSION["rol"] == 'commandant')) {
echo 'do some...';
}
array_key_exists is a nice alternative to using isset to check for keys:
if (array_key_exists('rol', $_SESSION) && ($_SESSION["rol"] != 'trainer' || $_SESSION["rol"] ==
'commandant')) {
echo 'do more...';
}
Hope that helps.
PS: #dexter solution with a in_array() will be better over time and easier to maintain.

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
}

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

?page=index $_GET

For this moment using this code:
if ($_GET['page'] == 'index'
and file_exists('./intl/tpl/' . $_GET['page'] . '.tpl')
or !file_exists('./intl/tpl/' . $_GET['page'] . '.tpl')
or !$_GET['page']) {
//code
} elseif ($_GET['page'] == 'multi'
and file_exists('./intl/tpl/' . $_GET['page'] . '.tpl')) {
//code 2
}
and so on...
Question 1: Does this code "good" ? Doesn't need any escaping or something ?
Question 2: ?page=logout doens't work, so i created logout.php which looks like:
<?php
require_once "./intl/config.php";
SessionDelete('logged_in');
SessionDelete('username');
SessionDelete('userid');
if ($user_admin != null) {
SessionDelete('inadmin');
if (SessionGet('s_order') != null or SessionGet('s_page_show_all') != null) {
SessionDelete('s_order');
SessionDelete('s_page_show_all');
}
}
header('Location: '.$config['indexurl'].'index.php');
?>
Maybe before sessions delete need session start and it's possible do that with ?page=logout ?
The code certainly can be improved:
Reorder the tests so that it will not generate E_NOTICE errors
Parenthesize so that operator precedence is immediately obvious
Use the && and || boolean operators (as garvey's comment says)
Doing this, you 'd have:
if (empty($_GET['page']) ||
!file_exists('./intl/tpl/' . $_GET['page'] . '.tpl') ||
($_GET['page'] == 'index' && file_exists('./intl/tpl/' . $_GET['page'] . '.tpl')) {
//code
}
} elseif ($_GET['page'] == 'multi' && file_exists('./intl/tpl/' . $_GET['page'] . '.tpl')) {
//code 2
}
Then, rewrite it some more to make it clear why you are doing what you do. This will also allow you to write simpler code. Simple is good.
// This way it's obvious that 'index' is the default page
$page = !empty($_GET['page']) ? $_GET['page'] : 'index';
if (!file_exists('./intl/tpl/' . $page . '.tpl')) {
$page = 'index'; // comment here saying that if a non-existing page is requested, we display the index instead
}
$template = './intl/tpl/' . $page . '.tpl';
// At this point, we know that $page has a value, and we know that $template exists, so:
switch($page) {
case 'index':
// code
break;
case 'multi':
// code2
break;
}
As for the second question: yes, you need to start the session before you are able to modify or destroy it.

Categories