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.


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

Thanks for reading!

Posted: 5 years ago

Updated: 5 years ago