Skip to content

Instantly share code, notes, and snippets.

@mbijon
Created November 4, 2012 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mbijon/4010764 to your computer and use it in GitHub Desktop.
Save mbijon/4010764 to your computer and use it in GitHub Desktop.
Rolling expiration with WordPress Transients: Each time the transient is accessed the expiration is delayed. Intended for rate-limiting (be careful not to share a transient btw multiple users). Might work better for micro-caching in the event a flood is n
$call_limit = 350; // API calls (in an hour)
$time_limit = 60 * 60; // 1 hour (in seconds)
$transient_name = $host . "_rate_limit"; // Using their host name as the unique identifier
// Check to see if there are any transients that match the name, if not create a new one
if ( false === ( $calls = get_transient( $transient_name ) ) ) {
$calls[] = time();
set_transient( $transient, $calls, $time_limit ); // Use an array of time() stamps for rolling effect
} else {
// There is already a transient with this name
$calls[] = time(); // Add a new time() stamp to the $calls array
set_transient( $transient, $calls, $time_limit ); // Reset the transient (w/ expiration time)
$call_count = count( $calls ); // How many calls have been made
if ( $call_limit < $call_count ) { // If we're over the call limit, remove expired timestamps
// Shift time from first element of array
while ( $call = array_shift( $calls ) ) {
// If time is >= current time - time limit, then it belongs in the array
// Add it back and reset the transient
if ( $call >= ( time() - $time_limit ) ) {
array_unshift( $calls, $call );
set_transient( $transient, $calls, $time_limit );
break; // Stop processing, we're within the time_limit time now.
}
}
// If we're still over the call limit, they've made too many requests in the time limit
if ( $call_limit <= count( $calls ) ) {
// The session needs to be killed
die('Error: You have exceeded your rate limit for API calls, only ' . $call_limit . ' API calls are allowed every ' . $time_limit . ' seconds.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment