2

I'm developing a site which posts a number of ajax calls from jquery to PHP and returns data from PhP to jquery.

Everything is working, but i'd to know if my approach to handling the calls is ok, in regard to security.

To run through my process;

functions.php file

  1. Setup wp_localize_script() & passed it the variables for ajax url and nonce -

     wp_localize_script( 'main', 'WP', array( 
         'AJAX_URL' => admin_url( 'admin-ajax.php'), 
         'NONCE' => wp_create_nonce( 'ajax_custom_nonce' ) 
     )); 
    

myscript.js file

  1. In my js file i've sent my post request using jquery;

    $.ajax({
        type : "post",
        url: WP.AJAX_URL,
        data: ({action : 'request_handler', 
            id : 'content_id',   
            nonce : WP.NONCE }),
        success: function(data) {}
    })
    

ajax.php file

  1. ajax.php file receives ajax post, calls request_handler();

    add_action("wp_ajax_nopriv_request_handler", "request_handler");
    add_action("wp_ajax_request_handler", "request_handler");
    
  2. request_handler() checks nonce, gets post id & runs switch statement to call required function.

     function request_handler() { 
         // check the nonce
         $nonce = $_POST['nonce'];
    
         if ( ! wp_verify_nonce( $nonce, 'ajax_custom_nonce' ) ) 
             die ('busted');
    
        $id = $_POST['id']; 
    
        switch ($id) {
            case 'vimeo_embed':
                // run vimeo();   
            break; 
            case 'popup':  
                require_once(TEMPLATEPATH . '/library/popup.php'); 
                load_popup();
            break;
    
            ....etc
        }
     } 
    
2
  • Your approach is OK. $id is used for switching only in your visible code. If you are going to use it in your processing you need to sanitize it. Your output should be properly escaped too. See codex.wordpress.org/Data_Validation
    – Upeksha
    Jan 1, 2013 at 16:21
  • I don't see a question here. Your code looks fine, but this site is a Q&A forum, not a code review forum. Closing for now.
    – EAMann
    Jan 20, 2013 at 5:05

0

Browse other questions tagged or ask your own question.