Jump to content

How to generate unique key of random numbers in PHP


Recommended Posts

Hi, I am looking for some example code that can help me to generate unique random string of numeric numbers in PHP Applications. I am hoping to resolve this issue with the help of tech developers working around & for this I have researched for many php questions & answers in various forums, but didn't get any satisfactory response. Hoping to get answer here.

Edited by requinix
Link to post
Share on other sites

You cannot have both random and unique: if it's completely random then there's a chance you'll generate the same string twice. But you can generate something unique that looks random, or you can pair something random with something unique into one string.

 

What are your criteria for this string?

Link to post
Share on other sites

A sufficiently big random number from a device like /dev/urandom will provide uniqueness, so this is perfectly valid.

 

PHP has a large variety of randomness APIs depending on the version:

To ensure global uniquess, you should generate 128 bits (16 bytes). You can then use hex-encoding or Base64-encoding to make the bytes human-readable. If you want a standardized format, there's UUID.

<?php

// Include the random_compat library if the PHP version is below 7



$random = random_bytes(16);

// hex encoding
$id = bin2hex($random);
echo $id, '<br>';

// a shorter alternative: Base64 encoding (uses characters a-z, A-Z, 0-9, +, /)
$id = rtrim(base64_encode($random), '=');
echo $id, '<br>';
Link to post
Share on other sites

Are you looking to create keys of some array or for table records? Or are you just looking for a single random number to use for some process? For the latter you have been provided answers. For the former, why? Just use a sequential number and then when you want to find one of them, use a random number function (limited by the max value already used) to select one of them.

Link to post
Share on other sites
This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.