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

时间:2015-03-12 15:52:18

标签: php session login-script

我一直在编写一个基本的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没有重定向,但我仍然登录。)

2 个答案:

答案 0 :(得分:0)

首先不要忘记添加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

答案 1 :(得分:0)

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

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";
}

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