簡體   English   中英

為什么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";
}

同樣不要忘記在使用會話變量之前開始會話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM