为什么这个变量总是返回true?
我正在尝试编写一个登录脚本。设置登录会话变量后,在主页上运行 isLoggedIn 函数。问题是变量 $loggedIn 总是返回 true。有人可以帮忙吗?
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 }
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. The problem is, that the variable $loggedIn is always returning 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 }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不是这个 if($_SESSION['logged'] = 1)
这是正确的 -> if($_SESSION['已记录'] == 1)
NOT THIS if($_SESSION['logged'] = 1)
THIS is correct -> if($_SESSION['logged'] == 1)
您正在使用赋值运算符
=
而不是条件运算符==
。它应该是:
赋值
=
的结果是右侧表达式,即 1,在本例中始终为 true。 :)You are using the assignment operator
=
instead of a conditional operator==
.It's supposed to be:
The result of an assignment
=
is the right hand side expression, which is 1, which is always true in this case. :)这是因为您将 $_SESSION['logged'] 设置为单个等于。使用双等号代替:
it's because you're setting $_SESSION['logged'] with the single equals. Use a double equals instead:
函数 isLoggedIn()
{
if($_SESSION['logged'] = 1)//将值'1'赋给$_SESSION['logged'],因此在这个if条件下,它检查$_SESSION['logged']是否有任何值,其中对于所有情况都适用(有效/无效)
返回真;
返回假;
}
$loggedIn = isLoggedIn();/$loggedIn 的值始终为 true 将
if($_SESSION['logged'] = 1) 更改为 if($_SESSION['logged'] == 1)
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;
return false;
}
$loggedIn = isLoggedIn();/those the value for $loggedIn will be always true
change the if($_SESSION['logged'] = 1) to if($_SESSION['logged'] == 1)