gpt4 book ai didi

mysql - 使用 WordPress get_results() 数据库函数是否可以防止 sql 注入(inject)

转载 作者:可可西里 更新时间:2023-11-01 07:38:35 24 4
gpt4 key购买 nike

似乎找不到答案,但想知道以下对数据库的查询是否容易受到 sql 注入(inject)的攻击。<​​/p>

$searchPostResults = $wpdb->get_results($querySearchVals, OBJECT);

这是使用的查询:

global $wpdb;
$offset = (isset($_POST["moreSearchResults"])) ? $_POST["searchOffset"] : 0;

$querySearchVals = "
SELECT DISTINCT post_title, ID
FROM {$wpdb->prefix}posts
WHERE (";

$sVals = array();
$sVals = explode(" ", $searchVal);

$lastIndex = intval(count($sVals)) - 1;
$orderByCaseVals = "";
for($i = 0; $i<count($sVals);$i++)
{
$querySearchVals .= " post_title LIKE '%$sVals[$i]%' ";
if($i != $lastIndex)
$querySearchVals .= " OR ";

$orderByCaseVals .= " WHEN post_title LIKE '%$sVals[$i]%' THEN ($i + 2) ";
}

$querySearchVals .= ")
AND {$wpdb->prefix}posts.post_type = 'post'
AND post_status = 'publish'
ORDER BY CASE
WHEN post_title LIKE '%$searchVal%' THEN 1
$orderByCaseVals
END
LIMIT $offset, 6;
";

干杯

最佳答案

好的,正如 tadman 所解释的,get_results 并不能阻止 sql 注入(inject)攻击。

需要使用prepare函数。

为了防止sql注入(inject),我重写了上面的代码:

global $wpdb;
$offset = (isset($_POST["moreSearchResults"])) ? $_POST["searchOffset"] : 0;

$querySearchVals = "
SELECT DISTINCT post_title, ID
FROM {$wpdb->prefix}posts
WHERE (";

$sVals = array();
$sVals = explode(" ", $searchVal);

$lastIndex = intval(count($sVals)) - 1;
$orderByCaseVals = "";
for($i = 0; $i<count($sVals);$i++)
{
$queryPrep = $wpdb->prepare(" post_title LIKE '%%%s%%' ", $wpdb->esc_like( $sVals[$i] ));
$querySearchVals .= $queryPrep;
if($i != $lastIndex)
$querySearchVals .= " OR ";

$queryPrep = $wpdb->prepare(" WHEN post_title LIKE '%%%s%%' THEN ($i + 2) ", $wpdb->esc_like( $sVals[$i] ));
$orderByCaseVals .= $queryPrep;
}

$querySearchVals .= ")
AND {$wpdb->prefix}posts.post_type = 'post'
AND post_status = 'publish'
ORDER BY CASE";

$queryPrep = $wpdb->prepare(" WHEN post_title LIKE '%%%s%%' THEN 1 ", $wpdb->esc_like( $searchVal ));
$querySearchVals .= $queryPrep;
$querySearchVals .= "
$orderByCaseVals
END
";

$queryPrep = $wpdb->prepare(" LIMIT %d, 12", $offset);
$querySearchVals .= $queryPrep . ";";

关于mysql - 使用 WordPress get_results() 数据库函数是否可以防止 sql 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46208353/

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