为什么 PHP if(!$_SESSION['username']) 返回 false

Why is PHP if(!$_SESSION['username']) is returning false

我一直在编写一个基本的 PHP 登录脚本,只是为了测试目的。

<?php
require 'config.php';
require 'connect.php';

// username and password sent from form 
$tbl_name = 'users';
$username=$_POST['username']; 
$password=$_POST['password']; 

// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result = mysqli_query($conn, $sql);

// Mysql_num_row is counting table row
$count = mysqli_num_rows($result);

// If result matched $username and $password, table row must be 1 row
if($count == 1)
{
// Register $username, $password and redirect to file "login_success.php"
$_SESSION["username"];
$_SESSION["password"]; 
header("location:../../home.php");
}
else {
echo "Wrong Username or Password";
}
?>

我可以毫无问题地解决这个问题,但是当它重定向到 home.php 时,这是我必须检查会话是否未注册的代码。

<?php
session_start();
if (!$_SESSION['username']) {
header("location:../../index.php");
}
?>

据我了解,这应该检查用户是否未登录,但是当我登录时它仍然将我重定向到 index.php。我怎样才能确保会话已注册并且没有任何反应(即我保持 home.php 没有重定向,但我仍然登录。)

首先不要忘记添加 session_start(); 以开始会话然后这样做,

// Register $username, $password and redirect to file "login_success.php"
$_SESSION["username"] = $username;
$_SESSION["password"] = $password; -->> Totally wrong, people don't put password in session

您需要在会话变量中保存一些东西

if($count == 1)
{
// Register $username, $password and redirect to file "login_success.php"
$_SESSION["username"]=$username;
$_SESSION["password"]; //Don't do this its a bad practice.
header("location:../../home.php");
}
else {
echo "Wrong Username or Password";
}

另外不要忘记在使用会话变量之前启动会话。