我有一个登录表单,当用户提供用户名和密码时,它会导致login.php
文件
session_start();
if ( isset( $_POST['username'], $_POST['password'] ) ) {
$user = $_POST['username'] ;
$pass = $_POST['password'] ;
$query = " MY QUERY ";
$result = mysql_query($query) or die('SQL ERROR:'.mysql_error());
$row = mysql_fetch_assoc($result);
if ($row) {
echo "query successfull wrote to DB";
unset($_SESSION);
$userName = $row['firstname'].' '.$row['lastname'];
$_SESSION['userNameSession'] = $userName;
$_SESSION['loginStatus'] = '1';
header('location:admin/admin.php');
}else{
echo "unscccessful login";
header('location:index.php');
}
}
当我尝试通过print_r($_SESSION)
从此文件打印会话时...它会显示会话及其变量值
Array ( [userNameSession] => full name [loginStatus] => 1 )
在我的admin/admin.php
(成功登录时打开)写
session_start();
print_r($_SESSION);exit;
如果尝试按print_r($_SESSION)
打印会话,则会将空数组显示为Array()
请帮忙。
答案 0 :(得分:3)
为什么要制作unset($_SESSION)
?这可能导致会话变量被删除但会话仍然存在。
如果要清除$_SESSION['LoginStatus']
和$_SESSION['userNameSession']
,请逐一清理(尽管这不是必需的,因为您稍后会重写其值):
unset($_SESSION['LoginStatus']);
unset($_SESSION['userNameSession']);
代码必须是这样的:
session_start();
if ( !empty($_POST['username']) && !empty($_POST['password']) ) {
$user = $_POST['username'] ;
$pass = $_POST['password'] ;
$query = " YOUR QUERY ";
$result = mysql_query($query) or die('SQL ERROR:'.mysql_error());
if (mysql_num_rows($result) > 0) {
//DELETE prints BEFORE header()!! -> echo "query successfull wrote to DB";
$row = mysql_fetch_assoc($result);
unset($_SESSION['userNameSession']);
unset($_SESSION['loginStatus']);
$userName = $row['firstname'].' '.$row['lastname'];
$_SESSION['userNameSession'] = $userName;
$_SESSION['loginStatus'] = '1';
header('location:admin/admin.php');
}else{
//DELETE prints BEFORE header()!! -> echo "unscccessful login";
header('location:index.php');
}
}
答案 1 :(得分:1)
您必须注意的一件重要事情:
请勿在标题前回显。我认为您的代码应该是这样的:
session_start();
if ( isset( $_POST['username'], $_POST['password'] ) ) {
$user = $_POST['username'] ;
$pass = $_POST['password'] ;
$query = " MY QUERY ";
$result = mysql_query($query) or die('SQL ERROR:'.mysql_error());
$row = mysql_fetch_assoc($result);
if ($row) {
unset($_SESSION);
$userName = $row['firstname'].' '.$row['lastname'];
$_SESSION['userNameSession'] = $userName;
$_SESSION['loginStatus'] = '1';
header('location:admin/admin.php');
}else{
header('location:index.php');
}
}
希望这有帮助。