当通过使用REST API和SQL查询时,我应该担心SQL注入吗$wpdb
?
例如,bellow是否易受sql注入攻击?
public static function get_post( WP_REST_Request $request ) {
global $wpdb;
$post_slug = $request->get_param( \'slug\' );
$sql_post_by_slug = "select * from wp_posts
where post_name=\'{$post_slug}\' and post_status=\'publish\'
limit 1;";
$post = $wpdb->get_results($sql_post_by_slug);
return $post[0];
}
register_rest_route(
\'reactapi/v1\',
\'/post/(?P<slug>[\\w\\W]+)\',
array(
\'methods\' => \'GET\',
\'callback\' => array(\'ReactApi\',\'get_post\'),
) );
我试图通过
\'
url中的字符,我发现它不起作用:
。。。reactapi/v1/post/slug\'additional-text变为。。。post\\u name=\'slug\\\'additional-text\'。。。
最合适的回答,由SO网友:Jacob Peattie 整理而成
对这根本不安全。您将用户输入直接放入数据库查询中。您需要使用$wpdb->prepare()
如果要在SQL中插入用户输入:
$post_slug = $request->get_param( \'slug\' );
$query = $wpdb->prepare(
"select * from wp_posts where post_name=%s and post_status=\'publish\' limit 1;",
$post_slug
);
$results = $wpdb->get_results( $query );