isset and if function in php with or operator - php

I have some PHP code to check user login status which check if session variables are set or cookies are set. If either of condition is true then it grand permission otherwise redirect to login page. Code looks like this :
if(isset($_SESSION["userid"]) || isset($_COOKIE["userid"]) && isset($_SESSION["username"]) || isset($_COOKIE["username"]) && isset($_SESSION["password"]) || isset($_COOKIE["password"])){
} else {
header("location : register.php");
}
The problem is that if session get destroyed (by closing browser or any other reason) it redirect the user to login page. But what it has to do is read cookies data and grant user access as cookies are still present (I've checked that cookies are still present by echo cookie data).

&& has a higher precedence than ||, so you need to guard the || with brackets. Also, having an empty if statement is just redundant:
if(!(isset($_SESSION["userid"]) || isset($_COOKIE["userid"]) ||
!(isset($_SESSION["username"]) || isset($_COOKIE["username"])) ||
!(isset($_SESSION["password"]) || isset($_COOKIE["password"]))) {
header("location : register.php");
}

You need to change your condition a bit because you are confusing it within SESSION and Cookie. Put them together with && and separate them with || like below:-
if((isset($_SESSION["userid"]) && isset($_SESSION["username"]) && isset($_SESSION["password"])) || (isset($_COOKIE["userid"]) && isset($_COOKIE["username"]) && isset($_COOKIE["password"]))){
// your action that you want
} else {
header("location : register.php");
}
Note:- Take care that same things are going to applied everywhere (on each other pages and conditions), otherwise you will face problem.
Also more dependency on cookie is not good, because it can be changed by the user any time.

You need to add a couple of breakers to group your statements like this:
if(
( isset($_SESSION["userid"]) || isset($_SESSION["username"]) && isset($_SESSION["password"]) )
||
( isset($_COOKIE["userid"]) || isset($_COOKIE["username"]) && isset($_COOKIE["password"]) )
){
// Your action
} else {
header("location : register.php");
}
Such statement will check if there is set COOKIE or SESSION and check or user_id or user name AND password.
If you need AND user_id AND username than replace || in brackets between isset() functions for this fields.

I think your if condition is missing some parenthesis. To make your code more readable you could create two functions
function isSessionValid()
{
return isset($_SESSION["userid"]) && isset($_SESSION["username"]) && isset($_SESSION["password"]);
}
function isCookieValid()
{
return isset($_COOKIE["userid"]) && isset($_COOKIE["username"]) && isset($_COOKIE["password"]);
}
and then use these functions in your if statement :
if (isSessionValid() || isCookieValid()) {
} else {
}

Related

Redirect error in php with isset and GET variable

I am trying to make some redirects to lock the page from having a different get variable from what i have defined. But the problem is that I am getting a redirect error which is
The page isn’t redirecting properly.
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies.
I tried different things but I could not solve this problem. I need your help please. It is to note that the variables w_news and the rest are coming from links on the page.
these are the following code which are in the header of the project:
// Redirect function
function redirect_to($redirect_link) {
header("Location: ". $redirect_link);
exit;
}
$redirect_link = "index.php?sec=w_news";
//if sec is empty i want to redirect to the above link
if (!isset($_GET['sec']) || isset($_GET['sec']) && $_GET['sec'] == "") {
redirect_to($redirect_link);
} else if (isset($_GET['sec']) && $_GET['sec'] != "w_news" || $_GET['sec'] != "pol" || $_GET['sec'] != "sci" || $_GET['sec'] != "tech" || $_GET['sec'] != "spo" || $_GET['sec'] != "covid19"){
// and if the value is not = to the named ones i want also to redirect
redirect_to($redirect_link);
}
Thank you in advance :)
<?php
if ($_GET['sec'] == "w_news" || $_GET['sec'] == "pol" || $_GET['sec'] == "sci" || $_GET['sec'] == "tech" || $_GET['sec'] == "spo" || $_GET['sec'] == "covid19")
{
// working validate
}
else
{
//failed redirect";
$redirect_link = "index.php?sec=w_news";
header("Location: ". $redirect_link);
}
?>

Using session to store cookies and check login

I am using $_SESSION to store cookies as I need certain variables to be set upon login.php to be used on other place.
On my login.php
if(!isset($_SESSION)) {
session_start();
}
$_SESSION['isLoggedIn'] = 1;
$_SESSION['loggedInID'] = $id;
$_SESSION['isAdmin'] = $isAdmin; // 1 for admin, else 0
On my admin.html page which will call admin.js that would do ajax call to admin.php upon load. I need to check whether is the user logged in is an admin.
I did this on my admin.php.
session_start();
if (!(isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] != 1)) {
echo 'Not logged in as admin';
}
But now on my admin page, admin.php keeps echo "Not logged in as admin";
Why is that so?
You need OR instead of AND:
if (!isset($_SESSION['isAdmin']) || $_SESSION['isAdmin'] != 1) {
Now, if the variable is set, the first condition is false so the second one will be checked. Only if the second condition is met (not logged in as admin), you will see the warning.
Well, lets say isset($_SESSION['isAdmin'] == true and lets say $_SESSION['isAdmin'] == 1. So currently your if looks like this:
if(!(true && 1!=1)) {
...
}
so you then get
if(!(true && false)) {
...
}
furthermore, you get
if(!(false)) {
...
}
which really means true. Try something like this instead:
session_start();
if (!isset($_SESSION['isAdmin']) || $_SESSION['isAdmin'] != 1) {
echo 'Not logged in as admin';
}
incase of $isAdmin = 1 in the example you give renders to:
if (!(true && false)) {
echo 'Not logged in as admin';
}
this is why you will get the echo result Not logged in as admin
Check if the variable is defined before see it's value
session_start();
if (isset($_SESSION['isAdmin']) {
if($_SESSION['isAdmin'] != 1) {
echo 'Not logged in as admin';
}
}

filter_input for session variables

Is there some equivalent of filter_input I can use with $_SESSIONas I would with $_POST?
When I tried it gives the error :
Warning: filter_input(): INPUT_SESSION is not yet implemented
session_start();
$x=filter_input(INPUT_SESSION, 'x');
if ($x){
echo $x;
}
php version: PHP Version 5.5.12-1+deb.sury.org~precise+1
I have the same problem like you. Maybe we are so rigorous but I solved the problem without compromising any security/filter.
I used filter_var instead of filter_input.
an example is like this:
session_start();
$_SESSION['baba'] = "co";
$ses = filter_var($_SESSION['baba']);
if (!empty($ses)) {
echo $ses;
}
Seems like $_SESSION doesnt work the same that $_SERVER.
After many combinations i had a similar issue. I'll leave some of my code after fixing so you can see the difference:
Here is the original code with warnings due to direct access to these variables
if ( (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == false) ||
($_SESSION['REMOTE_ADDR'] != $_SERVER['REMOTE_ADDR']) ||
(!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == false) ||
($_SESSION['HTTP_USER_AGENT'] != $_SERVER['HTTP_USER_AGENT'])
) {
header("Location: ../login.php");
}
Below is the code after including filters and cleared warnings
if ( (!isset($_SESSION['loggedin']) || (filter_var($_SESSION['loggedin']) == false)) ||
(filter_var($_SESSION['REMOTE_ADDR']) != filter_input(INPUT_SERVER,'REMOTE_ADDR')) ||
(!isset($_SESSION['loggedin']) || (filter_var($_SESSION['loggedin']) == false)) ||
(filter_var($_SESSION['HTTP_USER_AGENT']) != filter_input(INPUT_SERVER,'HTTP_USER_AGENT') )
) {
header("Location: ../login.php");
}

How do I add another check for what session is set when it's already checking for one?

I want to know how to make a second "check" on what session is set. I am currently using this code:
<?php
session_start();
require_once("../user/connect.php");
include "getn.php";
if($_SESSION['username'] != 'RBLXDev') {
die('lol failure');
}
?>
My current username is RBLXDev, but I want to make it check if the current username (stored in a session named username) is something like "waffle_".
I believe how you do the and statement in PHP is ||, but I don't know how to add to that code.
You can use any Logical Operator in you if statement to perform 2 or more checks -
using or / || -
if($_SESSION['username'] != 'RBLXDev' or $_SESSION['username'] != '...') { }
if($_SESSION['username'] != 'RBLXDev' || $_SESSION['username'] != '...') { }
using and / && -
if($_SESSION['username'] != 'RBLXDev' and $_SESSION['username'] != '...') { }
if($_SESSION['username'] != 'RBLXDev' && $_SESSION['username'] != '...') { }
Welcome to SO!
if($_SESSION['username'] != 'RBLXDev' && $_SESSION['username'] != 'waffle_')
Please read into php's logical operators.

Setting session variable as a number then checking isset against that variable number

I have created a simple PHP login system, I am fairly new to PHP in some ways. The login system doesn't use a database as its only one user.
<?php
if(isset($_SESSION['loggedin']))
{
die("You are already logged in!");
}
if(isset($_POST['submit']))
{
if ($_POST["Username"]=="****" && $_POST["password"]=="****")
{
$_SESSION['loggedin'] = "1";
print $_SESSION['loggedin'];
}
}
?>
Then for every other page I have a PHP checker with an if statement:
<?php
session_start(); // NEVER forget this!
if(!isset($_SESSION['loggedin'] = "1"))
{
die("To access this page, you need to <a href='login.php'>LOGIN</a>");
}
?>
It worked when I just set loggedin to 'YES' and then used the line
if(!isset($_SESSION['loggedin']))
But when I try to assign loggedin a number in this example 1, and then make the checker check that if its NOT the number 1 then die, like this:
if(!isset($_SESSION['loggedin'] = "1"))
it doesn't work. Can anyone tell me how I am going wrong?
Try using == instead of =. Using '=' will assign the value 1 to the session variable.
if(!isset($_SESSION['loggedin'] == "1"))
However, a better option would be:
if($_SESSION['loggedin'] != "1")
Using Yoda conditions and checking whether $_SESSION['loggedin'] is set, that would be:
if(!isset($_SESSION['loggedin']) || "1" != $_SESSION['loggedin'])
if( !isset($_SESSION['loggedin']) || $_SESSION['loggedin'] != "1" )
Also make sure that you have session_start() at the top of your first example.
<?php
session_start();
if(isset($_SESSION['loggedin']))
{
die("You are already logged in!");
}
if(isset($_POST['submit']))
{
if ($_POST["Username"]=="****" && $_POST["password"]=="****")
{
$_SESSION['loggedin'] = "1";
print $_SESSION['loggedin'];
}
}
?>
If you're using a String as a value, you can also use the php function strcmp($str1, $str2) for binary safe string comparison. So you may do this test:
if(isset($_SESSION['loggedin']) && strcmp($_SESSION['loggedin'], '1') == 0)
If the values on strcmp are equal, it evaluates to 0. If str1 is less than str2 it returns < 0 and if str1 is greater than str2 it returns > 0.
For more info: http://php.net/manual/en/function.strcmp.php

Categories