gpt4 book ai didi

php - 刷新后登录 session 被销毁

转载 作者:行者123 更新时间:2023-11-29 00:12:27 26 4
gpt4 key购买 nike

我在 Google 的帮助下制作了一个登录脚本,但问题是每次我刷新页面时它都会注销并将我重定向到登录页面。所以基本上我希望用户在输入他的详细信息后登录,而不是在单次刷新后注销。我的代码是:

<?php

if(!isset($_SESSION)){
session_start();
}

$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);

if ($username && $password)

{


$result = mysqli_query($con, "SELECT * FROM admin WHERE username='$username' ");

$numrows = mysqli_num_rows($result);

if($numrows !=0)
{
while($row = mysqli_fetch_assoc($result))
{
$dbusername = $row["username"];
$dbpassword = $row["password"];

}
if($username==$dbusername && $password==$dbpassword)
{

$_SESSION['username'] = $dbusername;
}
else
echo "Incorrect Password";
}
else
header("location: login.php");


}
else
header("location: login.php");
?>

最佳答案

mysqli_real_escape_string() REQUIRES 您要与数据库建立事件/已建立的连接。由于您在连接之前执行了 m_r_e_s() 调用,您将简单地返回 bool 值 FALSE 以表示失败。所以你在破坏你的“引用”值。

插入到字符串中的 bool 假值只会被转换为空字符串,因此您的查询开始看起来像

SELECT ... WHERE username=''
^---see the boolean false in there?

您的代码序列应该是:

session_start();
connect_to_db();
prepare_variables();
do_query();

既然您使用的是 mysqli,那么您为什么还要手动转义变量?您可以只使用准备好的语句 + 占位符并完全绕过这个问题。

关于php - 刷新后登录 session 被销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24396744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com