1

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:

  • Must be unique
  • Only int values, no letters
  • Length of 27 digits
  • Use an user id and time to make the ID unique

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?

3 Answers 3

4
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

Sign up to request clarification or add additional context in comments.

4 Comments

I don't know if this is really "unique". Are you sure that it's unique? Forever and ever?
Once times goes, never come back. that is timestamp :)
I think what he's asking is whether there's a chance of collision. But there shouldn't be.
You can use a combination of a unique id (say user_id) in your database + unique_timestamp to create a unique number.
1

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.

2 Comments

This is a good idea. I'll wait some minutes but I think your idea is great!
Array ( [] => ) mt_rand() expects parameter 1 to be integer, float given on line 5
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.