0

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'...

0

Yes. 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 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.