Security – Ajax & Nonce use-Collection of common programming errors


  • Cam

    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 and if theres any further security measures i could take or keep in mind.

    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':
                  require_once(TEMPLATEPATH . '/library/vimeo.php'); 
                  load_vimeo();  
              break; 
              case 'popup':  
                  require_once(TEMPLATEPATH . '/library/popup.php'); 
                  load_popup();
              break;
      
              ....etc
          }
       } 
      

    thanks


  • Mickle Foretic

    The code seems fine, I guess the only thing to watch for, is how you handle unexpected values of $id, i guess a default would work fine in that switch.