gpt4 book ai didi

php登录错误检查脚本与sql

转载 作者:行者123 更新时间:2023-11-29 22:32:34 24 4
gpt4 key购买 nike

我正在制作一个连接到数据库的网站和登录功能。我已经编写了脚本,它确实登录和注销,但即使表单字段为空,它也只是登录,例如,如果我没有在用户名和密码字段中输入任何内容,它仍然会登录。我已经检查并测试了我的数据库是与服务器上的 PHP 文件连接。在网上研究后我尝试了很多东西,但都浪费了我的时间,而且我仍然无法让它正常工作,

我的代码是:

<?php
if (isset($_POST['loginsubmit'])){

$query = "SELECT user_id, password FROM users WHERE username = '".$_POST['username']."'";
$result = mysql_query($query) or die (mysql_error());
$row = mysql_fetch_array($result);

if ($row['password'] == $_POST['pword']){

$_SESSION['id'] = $row['user_id'];
$_SESSION['loggedin'] = true;
}else{

$_SESSION['id'] = 0;
$_SESSION['loggedin'] = false;

}}

if (isset($_SESSION['loggedin'])==true){

echo "<p> Hello " . "$_POST[username]"." <a href='logout.php'>LogOut </a> </p>";
}else {
echo "<p>You are NOT logged in</p>\n";
}

我想做的是检查:

  • 已在表单中输入用户名
  • 已在表单中输入密码
  • 表单中输入的用户名/密码组合为正确,用户确实存在于数据库中。

最佳答案

看看“设置或不设置”的方法是否适合您。除了不使用任何 mysql_ 函数之外,我还指出了一些需要研究的内容:

<?php
// You probably have this, but make sure session_start() is on the top of page
session_start();
if (isset($_POST['loginsubmit'])){
// If you use PDO or mysqli_ with prepared statements,
// you don't need to escape the post, but in your case
// you do (sql injection hazard)
$query = "SELECT user_id, password FROM users WHERE username = '".mysql_real_escape_string($_POST['username'])."'";
$result = mysql_query($query) or die (mysql_error());
$row = mysql_fetch_array($result);

// You really need to insert encrypt/decrypt routine here for the password
// Storing plain-text passwords is bad news.

if (isset($row['password']) && ($row['password'] == $_POST['pword']))
$_SESSION['id'] = $row['user_id'];

// Don't even set a session attribute here.
// When you check stuff for logged in or logged out,
// you would just check if the $_SESSION['id'] is even set
// If it is, logged in, if not, then logged out
}

// The problem in your code is likely this line:
// if (isset($_SESSION['loggedin'])==true)
// Should be: if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true)
// That being said, I am not sure the point of setting session variables
// in the instance of not logged in.

// Check that it's set at all
if(isset($_SESSION['id']))
// You need to strip_tags or htmlspecialchars() this post
echo "<p> Hello " . htmlspecialchars($_POST['username'])." <a href='logout.php'>LogOut </a> </p>";
else
echo "<p>You are NOT logged in</p>\n";
?>

关于php登录错误检查脚本与sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29686268/

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