简体   繁体   English

为什么这个变量总是返回true?

[英]Why does this variable always return true?

I am trying to write a login script. 我正在尝试编写一个登录脚本。 After logging in a session variable is set, and on the main page, the isLoggedIn function is run. 登录后,会设置会话变量,并在主页面上运行isLoggedIn函数。 The problem is, that the variable $loggedIn is always returning true. 问题是,变量$ loggedIn总是返回true。 Can someone help? 有人可以帮忙吗?

function validateUser($user)
{
    if(isset($user)){
    session_regenerate_id ();//this is a security measure
    $_SESSION['logged'] = 1;
    $_SESSION['userid'] = $user;}
}
//Validates Login
function isLoggedIn()
{
    if($_SESSION['logged'] = 1)
        return true;
    return false;
}

$loggedIn = isLoggedIn();

if($loggedIn){ SHOW CONTENT FOR LOGGED IN USERS }

else { show content for users not logged in }

You are using the assignment operator = instead of a conditional operator == . 您正在使用赋值运算符 =而不是条件运算符 ==

It's supposed to be: 它应该是:

if ($_SESSION['logged'] == 1)
    return true;

The result of an assignment = is the right hand side expression, which is 1, which is always true in this case. 赋值=的结果是右侧表达式,即1,在这种情况下始终为真。 :) :)

it's because you're setting $_SESSION['logged'] with the single equals. 这是因为你用单个等号设置$ _SESSION ['logged']。 Use a double equals instead: 使用双等于:

function isLoggedIn()
{
    if($_SESSION['logged'] == 1)
        return true;
    return false;
}

function isLoggedIn() { if($_SESSION['logged'] = 1)//assigned value '1' to $_SESSION['logged'] so in this if condition it is checking if there is any value is $_SESSION['logged'], which will be true for all the cases (valid/invalid) return true; function isLoggedIn(){if($ _ SESSION ['logged'] = 1)//为$ _SESSION ['logged']分配值'1'所以在这个if条件下它检查是否有任何值是$ _SESSION ['记录'],对于所有情况都是如此(有效/无效)返回true; return false; 返回false; } }

$loggedIn = isLoggedIn();/those the value for $loggedIn will be always true $ loggedIn = isLoggedIn(); / $ loggedIn的值将始终为true

change the if($_SESSION['logged'] = 1) to if($_SESSION['logged'] == 1) 将if($ _ SESSION ['logged'] = 1)更改为if($ _ SESSION ['logged'] == 1)

不是这个 ($ _ SESSION ['logged'] = 1)这是正确的 - > if($ _ SESSION ['logged'] == 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM