0

I'm having code (user rates post) where I'm passing user_id and post_id via AJAX to the back-end. My concern is that user can change values in JS and pass another’s user id or post id. How do I prevent that?

Here is a simplified code (without nonces for the sake of example):

$('input[name="rate1"]:radio').change(function () {
    var rating = $("input[name='rate1']:checked").val();

    $.ajax({
        url : '<?php echo admin_url('admin-ajax.php') ?>',
        type : 'post',
        data : {
            'action': 'rate_the_post',
            'post_id': <?php echo $post_id; ?>,
            'user_id': <?php echo $user_id; ?>,
            'rating' : rating
        }
    }).done(function (data) {
        console.log(data);
    });
});

In the backend I get variables and update the post based on them:

function rate_post() {
    global $wpdb;

    $post_id = intval($_POST['post_id']);
    $user_id = intval($_POST['user_id']);
    $rating = intval($_POST['rating']);

    ...update DB with $wpdb;
}

So how do I make sure I have a valid user_id of current user and post_id of current post in the backend?

7
  • if a user is logged in, you don't need to submit her/his ID, since that variable is available in php anyways..?!
    – honk31
    Sep 3, 2018 at 14:23
  • @honk31 i don't think it's available via AJAX call, but if yes, how would you get it?
    – Runnick
    Sep 3, 2018 at 14:45
  • when the user is logged in, you could get its ID and credentials inside functions.php (or a plugin for that matter) via wp_get_current_user() or ID only via get_current_user_id()
    – honk31
    Sep 3, 2018 at 14:56
  • Sorry, I forgot to mention that I'm logging user via AJAX, so I don't have that available in functions.php
    – Runnick
    Sep 3, 2018 at 15:09
  • 2
    eather way, the user has to be logged in to vote, correct? so it will be available once s/he is..
    – honk31
    Sep 3, 2018 at 15:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.