Should I worry about SQL injection when using REST API and sql queries via $wpdb
?
For example, is the bellow vulnerable to sql injection?
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'),
) );
I tried to pass '
char in url and I see that it does't work:
...reactapi/v1/post/slug'additional-text turns to ...post_name='slug\\'additional-text'...
Should I worry about SQL injection when using REST API and sql queries via $wpdb
?
For example, is the bellow vulnerable to sql injection?
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'),
) );
I tried to pass '
char in url and I see that it does't work:
...reactapi/v1/post/slug'additional-text turns to ...post_name='slug\\'additional-text'...
1 Answer
Reset to default 0Yes. This is not secure at all. You're putting user input directly into a database query. You need to use $wpdb->prepare()
if you're inserting user input into 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 );