最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugin development - do I need to sanitize a shortcode's function input?

programmeradmin1浏览0评论

I'm using the following custom plugin to count the number of members in the MemberPress database:

function display_member_count( $atts ) {

    global $wpdb;
    $sql = "SELECT COUNT(`meta_key`) as count FROM `wp_usermeta` WHERE `meta_key` = 'mepr-address-state' && `meta_value` = '" . $atts[0] . "';";
    $myrows = $wpdb->get_results($sql);
    $member_count = $myrows[0]->count;

    return $member_count;
}

add_shortcode( 'member-count', 'display_member_count' );

I would then use the shortcode [member-count nsw] to display the number of members in NSW.

Do I need to sanitize $atts? If so, how please?

Help appreciated.

I'm using the following custom plugin to count the number of members in the MemberPress database:

function display_member_count( $atts ) {

    global $wpdb;
    $sql = "SELECT COUNT(`meta_key`) as count FROM `wp_usermeta` WHERE `meta_key` = 'mepr-address-state' && `meta_value` = '" . $atts[0] . "';";
    $myrows = $wpdb->get_results($sql);
    $member_count = $myrows[0]->count;

    return $member_count;
}

add_shortcode( 'member-count', 'display_member_count' );

I would then use the shortcode [member-count nsw] to display the number of members in NSW.

Do I need to sanitize $atts? If so, how please?

Help appreciated.

Share Improve this question asked Mar 30, 2019 at 7:54 SteveSteve 1,77719 gold badges67 silver badges115 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Of course you do have to sanitize it and escape it.

Otherwise any author/editor of the site will be able to perform any query on your database.

First of all you should never create SQL queries like you do in your code. Never concatenate the raw SQL with anything that is variable or comes from user.

You should use $wpdb->prepare for that.

So your code should look more like that:

$sql = "SELECT COUNT(meta_key) as count FROM {$wpdb->usermeta} WHERE meta_key = %s && meta_value = %s";
    $member_count = $wpdb->get_var( $wpdb->prepare( $sql, 'mepr-address-state', $atts[0] ) );

As you can see, there is also no point in getting all rows (there’s only one) and there’s no point in getting all columns (there also is only one).

That’s the escaping part that will save you from SQL injections.

But yes - most likely you should also put some validation in there - but it depends on what are the available values for that param.

发布评论

评论列表(0)

  1. 暂无评论