Skip to content
← Back to Snippets
Code

Rate Limit Bucket Snapshot

Builds a deterministic rate-limit bucket key and snapshot for login, form, or API throttling decisions.

Purpose

Builds a deterministic rate-limit bucket key and snapshot for login, form, or API throttling decisions.

Snippet details

ContextSecurityLevelAdvancedCopy-and-paste statusMarked safe after review.

Categories

  • Security

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Rate Limit Bucket Snapshot.
 *
 * Purpose:
 * Builds a stable rate-limit bucket key and review packet from request traits.
 *
 * @param string $scope Rate-limit scope, such as login or contact-form.
 * @param string $identity User, IP, or API identity value.
 * @param int $window_seconds Rate-limit window length.
 * @param int $current_time Current Unix timestamp.
 * @return array Rate-limit bucket snapshot.
 */
function ogSnippetRateLimitBucketSnapshot(string $scope, string $identity, int $window_seconds, int $current_time): array {
	$scope = trim(strtolower($scope));
	$identity = trim(strtolower($identity));

	if ($scope === '') {
		$scope = 'default';
	}

	if ($identity === '') {
		$identity = 'anonymous';
	}

	if ($window_seconds < 1) {
		$window_seconds = 60;
	}

	$window_start = $current_time - ($current_time % $window_seconds);
	$bucket_seed = $scope.'|'.$identity.'|'.$window_start;
	$bucket_key = hash('sha256', $bucket_seed);

	return array(
		'scope' => $scope,
		'identity_hash' => hash('sha256', $identity),
		'window_start' => $window_start,
		'window_seconds' => $window_seconds,
		'bucket_key' => $bucket_key
	);
}

$rate_snapshot = ogSnippetRateLimitBucketSnapshot('login', 'baltar@example.test', 300, time());

echo 'Battlestar rate bucket: '.$rate_snapshot['bucket_key'];