gpt4 book ai didi

php - 这个 PHP/MySQL 语句是否容易受到 SQL 注入(inject)攻击?

转载 作者:行者123 更新时间:2023-11-29 15:09:39 24 4
gpt4 key购买 nike

应该是一个简单的问题,我只是不熟悉 PHP 语法,我想知道以下代码是否可以免受 SQL 注入(inject)攻击?:

private function _getAllIngredients($animal = null, $type = null) {
$ingredients = null;
if($animal != null && $type != null) {
$query = 'SELECT id, name, brief_description, description,
food_type, ingredient_type, image, price,
created_on, updated_on
FROM ingredient
WHERE food_type = \'' . $animal . '\'
AND ingredient_type =\'' . $type . '\';';
$rows = $this->query($query);

if(count($rows) > 0) {

等等,等等

我用谷歌搜索了一下,似乎注入(inject)安全代码看起来与 WHERE food_type =\'' 不同。 $动物 .这里使用'\'语法。

抱歉,我不知道这里使用的是哪个版本的 PHP 或 MySQL,或者是否使用了任何第三方库,任何有专业知识的人都可以提供任何意见吗?

更新

语句中\的作用是什么?:

WHERE food_type = \'' . $animal . '\'  

在我的谷歌搜索中,我发现了许多对 mysql_real_escape_string 的引用...这是一个防止 SQL 注入(inject)和其他恶意行为的函数吗?

类声明是:

class DCIngredient extends SSDataController

那么可以想象其中包含mysql_real_escape_string吗?
我应该要求查看 SSDDataController 的实现吗?

最佳答案

是的此代码容易受到 SQL 注入(inject)攻击。

“\”仅转义引号字符,否则 PHP 认为引号将结束您的 (sql-) 字符串。

此外,当您将整个 SQL 字符串传递给 SSDataControler 类时,如果已注入(inject)准备好的字符串,则不再可能避免攻击。

因此SSDataControler 类在设计上已被破坏(易受攻击)。

尝试像这样更安全的事情:

$db_connection = new mysqli("host", "user", "pass", "db");
$statement = $db_connection->prepare("SELECT id, name, brief_description, description,
food_type, ingredient_type, image, price,
created_on, updated_on
FROM ingredient
WHERE food_type = ?
AND ingredient_type = ?;';");
$statement->bind_param("s", $animal);
$statement->bind_param("s", $type);
$statement->execute();

通过使用bind方法,您可以指定参数的类型(s表示字符串,i表示整数等),您将永远不会再考虑sql注入(inject)

关于php - 这个 PHP/MySQL 语句是否容易受到 SQL 注入(inject)攻击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1146396/

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