No cookie value on other pages - php

The page im posting to has the following code, and echo's the cookie correctly:
/* verify.php */
if ($age >= "21" && $location == "USA" && $cookie == "Y") {
$value = "1";
setcookie("age_verified", $value, time()+60*60*24*30);
header("Location: ../portal.php?cookieset");
}
elseif ($age >= "21" && $location == "USA") {
session_start();
$_SESSION['age_verified'] = "1";
header("Location: ../portal.php?sessionset");
}
On portal.php i am not able to echo the cookie, but the session shows up fine if that option is chosen.
/* portal.php */
session_start();
echo $_SESSION["age_verified"];
Result is "1"
/* portal.php */
echo $_COOKIE["age_verified"];
No Result
I'm trying to achieve something like the code block below, but it's not working properly since cookie doesn't echo a result
/* portal.php */
session_start();
if($_SESSION['age_verified']!="1"){
header("Location: index.php?no_session");
}
elseif ($_COOKIE['age_verified']!="1"){
header("Location: index.php?no_cookie");
}
else{
echo "";
}
What am i missing?

It would seem to me that $_SESSION['age_verified']!="1"||$_COOKIE['age_verified']!="1" is checking against EITHER session or cookie values. Cookie values are more persistent as they are stored on the user's machine, and session values only persist to a browsing session. They may not both be set.
In fact, looking at your logic on verify.php you are performing one action OR the other, not both. Hope this helps.

Related

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';
}
}

isset and if function in php with or operator

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 {
}

How To Redirect If Cookie Does Not Equal Vairable

I am struggling to redirect the user if the cookie does not equal a vairable. If it does equal the vairable, then it should continue the script. Here is my code to redirect :
if(empty($_GET)) {
//No variables are specified in the URL.
//Do stuff accordingly
echo "No variables specified in URL...";
} else {
//Variables are present. Do stuff:
$id = htmlspecialchars($_GET["id"]);
echo 'url query is ' . $id;
}
if(isset($_COOKIE['logged_in']) == $id)
{
header("Location: test.php");
}
if(isset($_COOKIE['logged_in']) != $id)
{
//continues the script
Please note that the vairable in the if statment ($id) is a vairable from the query of url; for example if the url is, "random.com/test.php?id=17" and the cookie equals 18 the script should redirect. However if url is, "random.com/test.php?id=17" and the cookie equals 17, then stay on the same page. Sorry if it sounds complecated.
It doesnt work as this code: It doesnt redirect no matter what the vairable equals. Thanks
Are you looking for something like this. If so, it should work for your case:
<?php
if(empty($_GET)) {
//No variables are specified in the URL.
//Do stuff accordingly
echo "No variables specified in URL...";
} else {
//Variables are present. Do stuff:
$id = htmlspecialchars($_GET["id"]);
echo 'url query is ' . $id;
}
if(isset($_COOKIE['logged_in']) && $_COOKIE['logged_in']==$id)
{
header("Location: test.php");
}
if(isset($_COOKIE['logged_in']) && $_COOKIE['logged_in']!=$id)
{
//continues the script
}
?>
A headers will apply only after it send to client. If you want immediately redirect, you can put exit(0) after header(...) in this case you are stop executing of the script and will send current headers to the browser which will redirect you.
if(isset($_COOKIE['logged_in']) && $_COOKIE['logged_in']==$id) {
header("Location: test.php");
exit(0);
}
//continues the script
The problem is that you are comparing the "value" of isset (the result) with the value of your GET parameter, $id:
if(isset($_COOKIE['logged_in']) == $id)
What this says is "determine if $_COOKIE['logged_in'] is set and compare that determination to $id". PHP will evaluate isset, which returns true or false (as it says in the documentation), and compare that true or false to the other side of the expression (==), meaning $id, which will never match given your examples. If you query "random.com/test.php?id=true" (or false) that might do what you are looking for.
The line you have does not mean "determine if $_COOKIE['logged_in'] is set and compare the value of $_COOKIE['logged_in'] to the value of $id", which I believe is what you are looking for. In that case, what you want to do is first check that $_COOKIE['logged_in'] is set and then check that the value of $_COOKIE['logged_in'] matches $id, like so:
if (isset($_COOKIE['logged_in']) && $_COOKIE['logged_in'] == $id)
If that doesn't make sense, here is a really explicit version that might be clearer as to what is actually going on:
if ((isset($_COOKIE['logged_in']) == true) && ($_COOKIE['logged_in'] == $id))
Hope that helps.
you should add another condition.
if(empty($_GET)) {
//No variables are specified in the URL.
//Do stuff accordingly
echo "No variables specified in URL...";
} else {
//Variables are present. Do stuff:
$id = htmlspecialchars($_GET["id"]);
echo 'url query is ' . $id;
}
if(isset($_COOKIE['logged_in']) && $_COOKIE['logged_in'] == $id)
{
header("Location: test.php");
}
if(isset($_COOKIE['logged_in']) && $_COOKIE['logged_in'] != $id)
{
//continues the script
or use this script
if(isset($_COOKIE['logged_in']))
{
if($_COOKIE['logged_in']==$id){
header("Location: test.php");
}
else{
//another condition to equal is not equal so directly we can use else
//continues the script
}
} else {
echo "Cookie not valid or available";
// redirect user
}

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

PHP if else confusion

i'm trying to make an image appearance and disappearance based on 3 condition,
condition A = when user is logged in and it's username fits the displayname(by using the GET function) then it should echo "yes"
condition B = When user is logged in and it's username does not fits the displayname then it should echo "no"
condition C = when user is not logged in then it should echo "no" too
(i swapped the image with yes and no for easier referencing)
By logging in, the user has a cookie which is set like below
setcookie("user", $user, $expire);
setcookie("loggedin", 1, $expire);
First i get the cookie which i set when user logins.
$user1 = $_COOKIE["user"];
$loggedin = $_COOKIE['loggedin'];
$user = strtoupper($user1);
then i get my player's name
$playername = $_GET['player'];
Now i do the conditions
$uplayername = strtoupper($playername);
function showplusicon(){
global $uplayername;
if(($loggedin = "1") and ($user == $uplayername)){
echo "yes";
}
else if (($loggedin = "1") and ($user != $uplayername)){
echo "no";
}
else{
echo "no";
}
}
I don't see what's the problem but it keeps being registered as condition B.
Single equal signs assign, not compare.
if(($loggedin == "1") and ($user == $uplayername)){
...
And since you really only have two output states, you shouldn't need 3 conditions; remove condition B.
The variable $loggedin isn't known inside your function showplusicon(). You will need to add it as a global along with global $uplayername.
function showplusicon(){
global $loggedin, $uplayername;
// etc
}
Since this was accepted but not totally complete, I'll just add that as others indicated, the == equality operator needs to be used instead of the = assignment operator.
if(($loggedin == "1")
^^^^
$loggedin = "1"
Surely this should be:
$loggedin == "1"
Otherwise I would echo $user and $uplayername to see if these differ.
First thing's first:
$loggedin = "1" is a bad idea, as you're actually giving $loggedin the value "1" instead of comparing. Use == or even === if you're sure about the datatype.
Further on, the $loggedin isn't available in the scope of showplusicon(), as you haven't declared it as a global like you did with $uplayername.
Fix the listed issues above and it should be working a bit better.
If you've got problems to understand your own code's logic, a simple way is to assign the conditions to self speaking variables to get used to it:
$userIsLoggedIn = $loggedin == "1";
$userIsPlayer = $user == $uplayername;
The variables make it easy to debug your code at the very beginning
var_dump($userIsLoggedIn, $userIsPlayer);
so to locate the actual errors:
The variable $loggedin is undefined
The if clauses are setting a value (=), not comparing it (== or ===).
You can then use additionally a more readable code-flow to make your decision more visible:
if ($userIsLoggedIn)
{ // user is logged in
if ($userIsPlayer)
{ // user is player
...
}
else
{ // user is not player
...
}
}
else
{ // user is not logged in
...
}
Depending of what you want to output, this can be simplified even:
if ($userIsLoggedIn && $userIsPlayer)
{
echo 'yes';
} else
{
echo 'no';
}
Hope this is helpful for you.
Your main problem is todo with global scope of your variables:
<?php
//Get cookie info
$cookie['user'] = $_COOKIE["user"];
$cookie['loggedin'] = (isset($_COOKIE['loggedin'])&&$_COOKIE['loggedin']=='1')?TRUE:FALSE;
//Set user array
$user['user'] = strtoupper($cookie['user']);
$user['loggedin'] = $cookie['loggedin'];
$user['player'] = $_GET['player'];
$user['uplayername']=strtoupper($user['player']);
function showplusicon(){
//Made $user array available within function
global $user;
if($user['loggedin'] === TRUE && $user['user'] == $user['uplayername']){
echo "yes";
}else{
echo "no";
}
}
?>

Categories