0

I am considering options to use in generating a 5 character unique string in php. Or if anyone have a better option. I'm not sure if substr will actually reduces the reliability of the uniqueness as well. All advise appreciated.

Option1:

$unique_id=substr(md5(time()), -5);

OR

Option2:

$unique_id=substr(uniqid, -5);
Lawrence
  • 717
  • 1
  • 12
  • 25
  • you can use first three character static and embed only two character at last it is useful for to easy identified if you use random then after when there is no of data is large then may be it match with some existing one – priya786 May 23 '15 at 07:27
  • Solution could be here - http://stackoverflow.com/questions/4356289/php-random-string-generator – Falt4rm May 23 '15 at 07:28
  • Option 3: Using PHP's [uniqid()](http://php.net/manual/en/function.uniqid.php), that does exactly this, creates an ID based on the time, just heed the warning in the docs. – adeneo May 23 '15 at 07:30

3 Answers3

0

This In built php function could help you.

rand(min,max);
Sagar
  • 642
  • 3
  • 14
0

Personally I would go with first option, but instead use something more like:

md5(uniqid(rand(), true))

adrian
  • 2,786
  • 2
  • 18
  • 33
-1

Use, as @Sagar said, the

rand(min,max);

Then store the values in a database. Before you're giving the users the random number, check if it already exists in the database. If it doesn't, move on and insert to the database.

Something like this:

$rand = rand(min,max);

    $sql = "SELECT randomNum FROM users WHERE randomNum = '$rand'";
    $result = mysql_query($sql);
    $count = mysql_num_rows($result);

    if ($count != 1){
        //insert to database
    }
mrfloden
  • 74
  • 7