gpt4 book ai didi

php - 如何更好地保护我的数据库连接

转载 作者:行者123 更新时间:2023-11-29 14:16:02 27 4
gpt4 key购买 nike

我被告知此代码是旧的连接方式,并且容易受到 SQL 注入(inject)的影响。我怎样才能保证它的安全?

这是我用来检查用户数据库并添加新用户(如果他们没有帐户)的代码。我尝试了 mysqli,但我认为我做得不对,所以我现在必须回到这个,直到我知道如何确保它的安全。

<?php
// Connect to the database(host, username, password)
$con = mysql_connect('localhost','user1','pass1');
if (!$con)
{
echo "Failed to make connection.";
exit;
}
// Select the database. Enter the name of your database (not the same as the table name)
$db = mysql_select_db('db1');
if (!$db)
{
echo "Failed to select db.";
exit;
}
// $_POST['username'] and $_POST['password'] are the param names we sent in our click event in login.js
$username = $_POST['username'];
$password = $_POST['password'];
// Select eveything from the users table where username field == the username we posted and password field == the password we posted
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . $password . "'";
$query = mysql_query($sql);
// If we find a match, create an array of data, json_encode it and echo it out
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
$response = array(
'logged' => true,
'name' => $row['name'],
'email' => $row['email']
);
echo json_encode($response);
}
else
{
// Else the username and/or password was invalid! Create an array, json_encode it and echo it out
$response = array(
'logged' => false,
'message' => 'Invalid Username and/or Password'
);
echo json_encode($response);
}
?>

最佳答案

来自用户的任何数据都应该通过 mysql_real_escape_string() 传递。有关使用该功能的更多信息,请参阅下面的 URL。这非常重要。

http://php.net/manual/en/function.mysql-real-escape-string.php

以下是有关 PHP 的 SQL 注入(inject)的更多信息:

http://php.net/manual/en/security.database.sql-injection.php

MySQLi 信息(除了 mysql_real_escape_string 之外的另一种技术):

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

编辑:好吧,我承认,我有点老派。 MySQLi 似乎绝对是最佳选择。我比较熟悉PHP3和PHP4开发。如果可以,请使用最后一个链接重新实现数据访问代码。

关于php - 如何更好地保护我的数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12649017/

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