我写了一个简单的作者订阅插件。基本上,它显示了一个类似于YouTube的订阅按钮。当一个(登录的)用户点击它时,他们会订阅该作者,并会收到他们帖子的通知。
我使用AJAX使按钮不刷新页面,并使用数据属性将作者ID发送到我的函数,但我不确定这种方法是否会带来任何风险。
<button class="subscribe_button" data-author-id="352" data-action="subscribe">
从理论上讲,是否有人可以更改此数据属性的值以导致SQL注入或其他操作?通过AJAX发布数据似乎非常容易受到攻击,这比仅仅是一个PHP文件更容易受到攻击。我有理由这样想吗?下面的代码是否有任何风险?
<script>
( function( $ ) {
var ajaxurl = "<?php echo admin_url(\'admin-ajax.php\'); ?>",
subscriptions_container = $(\'.subscriptions_container\');
$(subscriptions_container).on(\'click\', \'.subscribe_button\', function() {
// Disable button temporarily
$(this).unbind("click");
var thisButton = $(this);
// Define author_id and button action
var author_id = $(this).data( "author-id"),
action = $(this).data( "action") + \'_callback\';
// Data to be sent to function
var data = {
\'action\': action,
\'security\': \'<?php echo $ajax_nonce; ?>\',
\'author_id\': author_id
};
// Send data with AJAX
jQuery.post(ajaxurl, data, function(response) {
thisButton.closest(\'.subscriptions\').replaceWith(response);
});
});
} )( jQuery );
</script>
和我的PHP回调函数:
function subscribe_callback() {
check_ajax_referer( \'*****\', \'security\' );
if ( is_user_logged_in() ) {
global $wpdb;
$table_name = $wpdb->prefix . "subscriptions";
// Check if author_id is posted and if it\'s a number
if ( isset($_POST[\'author_id\']) && is_numeric($_POST[\'author_id\']) ) {
$author_id = $_POST[\'author_id\'];
$subscriber_id = get_current_user_id();
// check if author is not subscribing to himself, if not then add database query
if ( $author_id != $subscriber_id ) {
if ( $wpdb->insert(
$table_name,
array(
\'subscriber_user_id\' => $subscriber_id,
\'author_user_id\' => $author_id,
\'email_notification\' => \'yes\',
\'subscription_date\' => current_time( \'mysql\' )
),
array(
\'%d\',
\'%d\',
\'%s\',
\'%s\'
)
) !== FALSE ) {
// add subscriber to usermeta
$author_subscriber_count = get_user_meta($author_id, \'subscribers\', true);
$author_subscriber_count++;
update_user_meta($author_id, \'subscribers\', $author_subscriber_count);
echo subscribe_button($author_id);
}
}
}
}
wp_die();
} add_action( \'wp_ajax_subscribe_callback\', \'subscribe_callback\' );