Reputation: 5251
I'm currently searching for a good way to generate a unique random number for SEPA transactions (End-to-End reference) with 27 digits in PHP. My requirements are:
I've tried this solution here but this only gives me a string with letters and numbers:
md5( uniqid( mt_rand(), true ) );
Does anyone has a lightweight solution or idea?
Upvotes: 1
Views: 2570
Reputation: 41
To get a 27-digit integer, you can take the first 27 characters of the hexadecimal hash and convert it to an integer.
try this:
function generateUniqueRandomInt($userId) {
$uniqueString = $userId . uniqid('', true); // Concatenate user ID and unique ID
$hashedString = hash('sha256', $uniqueString); // Generate SHA-256 hash
$first27Digits = substr($hashedString, 0, 27); // Take the first 27 characters
$uniqueNumber = (int) $first27Digits; // Convert to integer
return str_pad($uniqueNumber, 27, '0', STR_PAD_LEFT); // Pad with leading zeros if needed
}
You can use this function to generate a unique random integer number with 27 digits:
$userID = 12345; // Replace with the actual user ID
$uniqueRandomNumber = generateUniqueRandomInt($userID);
echo $uniqueRandomNumber;
Upvotes: 0
Reputation: 5506
echo $bira = date('YmdHis').rand(1000000000000,9000000000000);
echo "<br/>";
echo strlen($bira);
Add the time stamp in the front, so it will be unique always.
OR echo $bira = time().rand(10000000000000000,90000000000000000);
outoput:
201901220142532979656312614
27
Upvotes: 4
Reputation: 42304
How about this:
$array = [];
$numberOfTransactions = 1;
while (count($array) < $numberOfTransactions) {
$rand = mt_rand(100000000000000000000000000, 999999999999999999999999999);
$array[$rand] = $rand;
}
print_r($array);
Associative array keys are unique, so you won't get any duplicates.
Upvotes: 1