Doug's Blog

Invalidating form tokens in Drupal 7

I wanted to invalidate the CSRF token generated by drupal_get_token once the user had submitted a form, to ensure that we didn’t get a double submit. Drupal 7 generates tokens based on a combination of things, including the PHP session id. A simple call to session_regenerate_id() will cause the token generated by drupal_get_token to change and invalidate previous tokens.

Example:

$params = drupal_get_query_parameters();
if (drupal_valid_token($params['token'], TOKEN_NAME)) {
//do protected action
session_regenerate_id();
}
$token = drupal_get_token(TOKEN_NAME);