简体   繁体   English

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

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

I have been coding a basic PHP Login script just for testing purposes. 我一直在编写基本的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";
}
?>

I am able to get through this with no problem, but when it redirects to home.php, here is the code I have to check if session is not registered. 我能够顺利通过此操作,但是当它重定向到home.php时,这是我必须检查会话是否未注册的代码。

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

From what I understand, this is supposed to check if the user is not logged in, however when I login it still redirects me to index.php. 据我了解,这应该检查用户是否未登录,但是当我登录时,它仍然会将我重定向到index.php。 How can I make sure the session is registered and nothing happens (ie I stay on home.php with no redirect, but I'm still logged in.) 我如何确保会话已注册并且什么都没有发生(即,我没有重定向就留在home.php上,但是我仍然登录)。

First of all dont forget to add session_start(); 首先不要忘了添加session_start(); in order to start the session then do like this, 为了开始会议,然后这样做

// 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

You need to save save something in session variable 您需要保存将某些内容保存在会话变量中

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

Also don't forget to start session before using session variable. 同样不要忘记在使用会话变量之前开始会话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM