18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8<br />

Handling AJAX callbacks securely<br />

<strong>Drupal</strong> 7 comes with an enhanced AJAX framework that makes it easy to build<br />

interactive display elements for pages and forms. The security problem for <strong>Drupal</strong><br />

is that AJAX callbacks take the form of menu callbacks, which unlike most <strong>Drupal</strong><br />

forms, are essentially GET requests to the browser. This fact means that any request<br />

to an AJAX callback must be treated as malicious and that all such requests must be<br />

tested for validity before an AJAX response can be sent.<br />

Using AJAX in forms<br />

When using the #ajax element with the Forms API, <strong>Drupal</strong> automatically secures<br />

the AJAX callback by checking the validity of the form request. This action only<br />

works, of course, if you follow the FormsAPI correctly. Using the #ajax form<br />

element triggers the ajax_get_form() function, which uses form_build_id to test<br />

for validity:<br />

function ajax_get_form() {<br />

$form_state = form_state_defaults();<br />

$form_build_id = $_POST['form_build_id'];<br />

// Get the form from the cache.<br />

$form = form_get_cache($form_build_id, $form_state);<br />

if (!$form) {<br />

// If $form cannot be loaded from the cache, the form_build_id<br />

// in $_POST must be invalid, which means that someone<br />

// performed a POST request onto system/ajax without actually<br />

// viewing the concerned form in the browser.<br />

// This is likely a hacking attempt as it never happens under<br />

// normal circumstances, so we just do nothing.<br />

watchdog('ajax', 'Invalid form POST data.', array(),<br />

WATCHDOG_WARNING);<br />

drupal_exit();<br />

}<br />

// ...<br />

As we saw in the preceding section that form_build_id ensured that the form<br />

request was issued by the <strong>Drupal</strong> site and was valid.<br />

[ 235 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!