I'm writing a backend validation function to prevent multiple submission for comments by logged in users in Drupal. Following is my code:
function MYMODULE_form_comment_form_alter( &$form, &$form_state, $form_id ) {
if( user_is_logged_in() ) {
$unique_bytes = openssl_random_pseudo_bytes( 8 );
$unique_id = bin2hex( $unique_bytes );
$session_key = 'comment_form_token_' . $form['form_id']['#id'];
$_SESSION[$session_key] = $unique_id;
$form['one_time_token'] = array(
'#type' => 'hidden',
'#value' => $unique_id,
);
$form['#validate'][] = '_MYMODULE_comments_validate_one_time_token';
}
}
function _MYMODULE_comments_validate_one_time_token( $form, &$form_state ) {
if( user_is_logged_in() ) {
$form_id = $form['form_id']['#id'];
$session_key = 'comment_form_token_' . $form_id;
$one_time_token = $form_state['values']['one_time_token'];
if( isset( $_SESSION[$session_key] ) && $_SESSION[$session_key] === $one_time_token ) {
unset( $_SESSION[$session_key] );
}
else {
form_set_error( 'comment_body', t( 'Please make sure that you have submitted this form only once.' ) );
}
}
}
The problem is that when the user submits the form multiple times by clicking the Submit button extremely fast, the one_time_token field's value gets updated automatically rather than submitting the original value.
To elaborate further, if my initial field value on form load was e8ac1824bf894e12, session value for that was also e8ac1824bf894e12 and submitted value was also e8ac1824bf894e12. But on processing second submission, my session value is 153695ec028bf151 but I expect my submitted values to stay e8ac1824bf894e12 but somehow that also changes to 153695ec028bf151.
Is there a way I can prevent that?