I have written a simple author subscription plugin. Basically, it shows a subscribe button similar to YouTube. When a (logged in) user clicks on it, they subscribe to that author, and will get notified by their posts.
I'm using AJAX to make the button not refresh the page, and a data-attribute to send the author ID to my function, but I'm not sure if this approach causes any risks.
<button class="subscribe_button" data-author-id="352" data-action="subscribe">
Could someone theoretically change this data-attribute's value to cause an SQL injection or something? It seems that posting data through AJAX is very vulnerable to attacks, more so than if it were just a PHP file. Am I justified into thinking this? Are there any risks involved with my code below?
<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>
And my PHP callback function:
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' );