WordPress Ajax Data Security

There are a few things you can do to make more secure:

First the Ajax call it self should be made with a WordPress nonce like you said:

<script type="text/javascript" >
    jQuery(document).ready(function($) {
        var data = {
            action: 'ACTION_NAME',
            Whatever_data: 1234,
            _ajax_nonce: <?php echo wp_create_nonce( 'my_ajax_nonce' ); ?>
        };
        $.post(ajaxurl, data, function(response) {
            alert('Got this from the server: ' + response);
        });
    });
</script>

In the above code mind the two attributes action and _ajax_nonce which both are needed to verify the call to admin-ajax.php, in the first few lines of code it check if an action was sent to the server and if not then it die()‘s (FIRST CHECK) then using that action you with an action hook you call your own ajax function:

//if you want only logged in users to access this function use this hook
add_action('wp_ajax_ACTION_NAME', 'my_AJAX_processing_function');

//if you want none logged in users to access this function use this hook
add_action('wp_ajax_nopriv_ACTION_NAME', 'my_AJAX_processing_function');

and if you want both logged in users and none logged in visitors to access this function the use both hooks (SECOND CHECK).

then in you ajax function the first thing you should do is check for the ajax referrer (THIRD CHECK):

function my_AJAX_processing_function(){
   check_ajax_referer('my_ajax_nonce');
   //do stuff here
}

next when running queries on database with user input you should use $wpdb->prepare for escaping and validation so instead of:

$query = "SELECT `id` FROM table WHERE `user_id` = $myid;";
$data = $wpdb->get_col( $query )

use:

$data = $wpdb->query( $wpdb->prepare("SELECT `id` FROM table WHERE `user_id` = %d",$myid));

Leave a Comment