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";
}
}
?>
Related
This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 years ago.
I am trying to show a different navigation bar depending on a users authority. Only problem is that when i log on to the system it shows the first else if, regardless of the authority of the user. To ensure that the problem is in the loop i have tried switching the else ifs and the same happened. the code is in an external php file and i call the function in the top of each page. any suggestions ?
function checkAuth() {
session_start();
if(!isset($_SESSION['role'])) {
require_once('menu.php');
} else if ($_SESSION['role'] = "registered") {
require_once('regnav.php');
} else if ($_SESSION['role'] = "admin") {
echo "FDGFGFD";
require_once('adminnav.php');
}
}
Your issue is with this part: $_SESSION['role'] = "registered". The single = means you are assigning the value "registered" to variable $_SESSION['role'].
If you are evaluating to check something, you need to use == i.e. $_SESSION['role'] == "registered"
You'll have the same issue with the second elseif
You need to use a double = sign for any condition check. For any condition check in if or else if, you have to use == in the middle of the variables.
If you use only = that means it assigning the value in the $_SESSION['role']. Also you can use === for checking the value as well as the type of the variable.
Valid function is:
function checkAuth()
{
session_start();
if(!isset($_SESSION['role']))
{
require_once('menu.php');
}
else if ($_SESSION['role'] == "registered"){
require_once('regnav.php');
}
else if ($_SESSION['role'] == "admin"){
echo "FDGFGFD";
require_once('adminnav.php');
}
}
?>
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';
}
}
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
ok forgive my technique in writing here, but i can't seem to understand why this code recognizes things and then doesn't recognize some other things.
my code:
if (!isset($id)) {
$_SESSION["logged_in"] = False;
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
if ($_SESSION["logged_in"] = False)
{ echo "session variable is set at False"; }
if ( $_SESSION["logged_in"] = True)
{ echo "session variable is set at True"; }
}
now as I see it, if it enters this bit of code at all, the first thing that happens should be that the variable gets set to "false". elsewhere in some code not shown it gets set to true and that part works fine but when i try to force it into this for a false setting it remains true.. can anyone see why this wouldn't get set to "False" at this point in the execution?
You should be using == for comparison here, not = for assignment:
if ($_SESSION["logged_in"] = False)
// ---------------^^^
// Should be
if ($_SESSION["logged_in"] == False)
// Also here:
if ( $_SESSION["logged_in"] = True)
//--------------------------^^
// Should be
if ($_SESSION["logged_in"] == True)
You are making a classic mistake by assigning the variable in your if statement instead of comparing it. So, change your if statements to:
if ($_SESSION["logged_in"] == false)
Instead of (where you are assigning):
if ($_SESSION["logged_in"] = false)
By the way, you're statement has now some duplication since the variable itself already is true of false. So, there is no need to check it against the boolean. So, this can be enough:
if ($_SESSION["logged_in"]) //equals true if user is logged in
if (!$_SESSION["logged_in"]) // equals true if user is NOT logged in
You need == or ===
Using = means its equal :)
if (!isset($id)) {
$_SESSION["logged_in"] = False;
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
if ($_SESSION["logged_in"] == False)
{ echo "session variable is set at False"; }
if ( $_SESSION["logged_in"] == True)
{ echo "session variable is set at True"; }
}
You should be using the == operator rather than = in your if statements.
EG
if ($_SESSION["logged_in"] == False)
How can I compare two variable strings, would it be like so:
$myVar = "hello";
if ($myVar == "hello") {
//do code
}
And to check to see if a $_GET[] variable is present in the url would it be like this"
$myVars = $_GET['param'];
if ($myVars == NULL) {
//do code
}
$myVar = "hello";
if ($myVar == "hello") {
//do code
}
$myVar = $_GET['param'];
if (isset($myVar)) {
//IF THE VARIABLE IS SET do code
}
if (!isset($myVar)) {
//IF THE VARIABLE IS NOT SET do code
}
For your reference, something that stomped me for days when first starting PHP:
$_GET["var1"] // these are set from the header location so www.site.com/?var1=something
$_POST["var1"] //these are sent by forms from other pages to the php page
For comparing strings I'd recommend using the triple equals operator over double equals.
// This evaluates to true (this can be a surprise if you really want 0)
if ("0" == false) {
// do stuff
}
// While this evaluates to false
if ("0" === false) {
// do stuff
}
For checking the $_GET variable I rather use array_key_exists, isset can return false if the key exists but the content is null
something like:
$_GET['param'] = null;
// This evaluates to false
if (isset($_GET['param'])) {
// do stuff
}
// While this evaluates to true
if (array_key_exits('param', $_GET)) {
// do stuff
}
When possible avoid doing assignments such as:
$myVar = $_GET['param'];
$_GET, is user dependant. So the expected key could be available or not. If the key is not available when you access it, a run-time notice will be triggered. This could fill your error log if notices are enabled, or spam your users in the worst case. Just do a simple array_key_exists to check $_GET before referencing the key on it.
if (array_key_exists('subject', $_GET) === true) {
$subject = $_GET['subject'];
} else {
// now you can report that the variable was not found
echo 'Please select a subject!';
// or simply set a default for it
$subject = 'unknown';
}
Sources:
http://ca.php.net/isset
http://ca.php.net/array_key_exists
http://php.net/manual/en/language.types.array.php
If you wanna check if a variable is set, use isset()
if (isset($_GET['param'])){
// your code
}
To compare a variable to a string, use this:
if ($myVar == 'hello') {
// do stuff
}
To see if a variable is set, use isset(), like this:
if (isset($_GET['param'])) {
// do stuff
}
All this information is listed on PHP's website under Operators
http://php.net/manual/en/language.operators.comparison.php