Recently looking at the session of the question, you need to determine whether the user login, I found the following 2 ways to successfully determine whether to log on the issue.
The code is as follows:
第一种:if(empty($_SESSION)){ echo '您还未登录,请登录';}else{ echo '欢迎'.$_SESSION['uname'].' 这里是主页 '; echo '退出
';}第二种:if(!isset($_SESSION['uname'])){ echo '您还未登录,请登录
';}else{ echo '欢迎'.$_SESSION['uname'].' 这里是主页 '; echo '退出
';}
Question: In the second Judgment statement, if you write only $_session instead of $_session[' uname ', you will get an error, and if you use the first method, either $_session[' uname ' in the parentheses behind the empty or $_ The session is no problem, what is the reason? Which of the two methods would be better? Or is it a little safer? Thank you
Reply content:
Recently looking at the session of the question, you need to determine whether the user login, I found the following 2 ways to successfully determine whether to log on the issue.
The code is as follows:
第一种:if(empty($_SESSION)){ echo '您还未登录,请登录';}else{ echo '欢迎'.$_SESSION['uname'].' 这里是主页 '; echo '退出
';}第二种:if(!isset($_SESSION['uname'])){ echo '您还未登录,请登录
';}else{ echo '欢迎'.$_SESSION['uname'].' 这里是主页 '; echo '退出
';}
Question: In the second Judgment statement, if you write only $_session instead of $_session[' uname ', you will get an error, and if you use the first method, either $_session[' uname ' in the parentheses behind the empty or $_ The session is no problem, what is the reason? Which of the two methods would be better? Or is it a little safer? Thank you
It is recommended to use the second type. In the correct use of the second kind of premise, the code will be more rigorous.
Empty is null, isset is whether the variable exists.
As long as you open the session function, Session_Start (), then there will be a number of variable $_session exist.
But if you are not logged in, $_session is just an empty array, only you log in, you will go to $_session this data write data, such as
$_session[' uname '.
So the second only write $_session will be the cause of the error, is that you have not landed, so $_session[' uname '] does not exist, but $_session as an empty array is present.
Empty determines whether the parameter is considered empty. Even if the parameter exists, but his value is false, the parameter will still be considered empty.
if (Isset ($_session[' uname ')) &&!empty ($_session[' uname ')) {//This is good.
}
The difference between isset and empty: Empty () and isset () deal with objects without defining variables, 0, empty strings.
如果变量为0,则empty()会返回TRUE,isset()会返回TRUE; 如果变量为空字符串,则empty()会返回TRUE,isset()会返回TRUE; 如果变量未定义,则empty()会返回TRUE,isset()会返回FLASE;