How to Change the Cache Time on Your Form Token

Ready to take control of your form token cache time? In this tutorial, we’ll show you how to customize the duration for which your form tokens remain valid using PHP code.

First, let’s delve into how form tokens function. Each form is assigned a unique token that expires and resets after a set period. This security measure prevents spam by rejecting direct $_POST requests made by spammers, as the form token must be included for submission to be accepted. Even attempts to hard code the token are thwarted, as each token is unique and has a finite lifespan.

Adding the code snippet

If you would like to control the cache time for the form tokens, just copy this snippet to your site and adjust the times as needed.

If you need assistance in how and where to add snippets to your site, please review this tutorial.


/**
 * Extend cache time on form tokens before today.
 *
 * @link https://wpforms.com/developers/how-to-change-the-cache-time-on-your-form-token
 */

function example_add_longer_token_time_before( $times ) {
    // Allow the token to persist for 3, 4, and 5 days
    $times[] = 3 * DAY_IN_SECONDS;
    $times[] = 4 * DAY_IN_SECONDS;
    $times[] = 5 * DAY_IN_SECONDS;

    return $times;
}
add_filter( 'wpforms_form_token_check_before_today', 'example_add_longer_token_time_before' );

/**
 * Extend cache time on form tokens before today.
 *
 * @link https://wpforms.com/developers/how-to-change-the-cache-time-on-your-form-token
 */

function example_add_longer_token_time_after( $times ) {
    // Allow the token to persist for 1 day
    $times[] = DAY_IN_SECONDS;

    return $times;
}
add_filter( 'wpforms_form_token_check_after_today', 'example_add_longer_token_time_after' );

It’s important to clarify the functionality of the snippet regarding the cache time for form tokens. When we mention in the comment, allowing the token to persist for 3, 4, and 5 days, it means that the token will remain valid for up to the specified duration. For example, setting $times[] = 5 * DAY_IN_SECONDS allows the token to persist for a maximum of 5 days. However, it doesn’t guarantee that the token will last exactly 5 days. Instead, it may expire earlier if used or invalidated for any reason.

And that’s all you need to change the cache time on form tokens! Are you using GDPR but can’t get the flag on the Smart Phone form field to load correctly? No worries, just check out our snippet on How to Enable GDPR Without Removing the Smart Phone IP Auto-detection.

Reference Filters