我正在为我的网站创建一个登录系统,并且在用户登录后无法打印出用户名。
从数据库验证后我已经这样做了:
$_SESSION['userName'];
$_SESSION['password'];
header("location:success.php");
这是在success.php文件中打印用户名的代码:
session_start();
if($_SESSION['userName']!='')
{
header("location:login_form.php");
}
else
{
echo '<h2>Successfully Login <br /> Welcome '.$userName.'</h2>';
echo '<a href="logout.php"> Log Out</a>';
}
但不打印用户名。
答案 0 :(得分:2)
我想你想要:
echo '<h2>Successfully Login <br /> Welcome '.$_SESSION['userName'].'</h2>';
和
if($_SESSION['userName']!='')
应该是
if($_SESSION['userName']=='')
答案 1 :(得分:2)
首先,您没有将会话分配给任何值。
$_SESSION['userName'];
$_SESSION['password'];
header("location:success.php");
应该是:
$_SESSION['userName'] = 'My Username';
$_SESSION['password'] = 'My Password';
header("location:success.php");
其次,您尚未定义变量$userName
。将其更改为:$_SESSION['userName']
。
另一方面,您不应该在会话中存储密码,在使用die()
重定向用户后,您应该添加exit()
或header()
。
修改
重新阅读您的代码。虽然我之前的回答者建议你改变这一行:
if ($_SESSION['userName'] != '')
为:
if ($_SESSION['userName'] == '')
使用逻辑运算符检查会话是否存在实际上是不好的做法。正确的方法是使用isset()
函数:
if (isset($_SESSION['userName']))
祝你好运!
答案 2 :(得分:0)
这一行:
if($_SESSION['userName']!='')
应该是:
if($_SESSION['userName']=='')
答案 3 :(得分:0)
除非您在其他地方省略了代码,否则未定义此变量:$userName
您不会将其定义为变量。尝试:
$userName= $_SESSION['userName'];
$password = $_SESSION['password'];