Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random string from 4 to 8 characters in PHP

Tags:

I need to generate a string using PHP, it need to be unique and need to be from 4 to 8 characters (the value of a variable).

I thought I can use crc32 hash but I can't decide how many characters, but sure it will be unique. In the other hand only create a "password generator" will generate duplicated string and checking the value in the table for each string will take a while.

How can I do that?

Thanks!


Maybe I can use that :

  function unique_id(){   $better_token = md5(uniqid(rand(), true));   $unique_code = substr($better_token, 16);   $uniqueid = $unique_code;   return $uniqueid;   }    $id = unique_id(); 

Changing to :

  function unique_id($l = 8){   $better_token = md5(uniqid(rand(), true));       $rem = strlen($better_token)-$l;   $unique_code = substr($better_token, 0, -$rem);   $uniqueid = $unique_code;   return $uniqueid;   }    echo unique_id(4); 

Do you think I'll get unique string each time for a goood while?

like image 294
Jeremy Dicaire Avatar asked Oct 17 '10 18:10

Jeremy Dicaire


People also ask

How to generate random characters in PHP?

Using str_shuffle() Function: The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter.

What is Mt_rand function in PHP?

The mt_rand() function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.


1 Answers

In short, I think you'll get a pretty good random value. There's always the chance of a collision but you've done everything you can to get a random value. uniqid() returns a random value based on the current time in microseconds. Specifying rand() (mt_rand() would be better) and the second argument as true to uniqid() should make the value even more unique. Hashing the value using md5() should also make it pretty unique as even a small difference in two random values generated should be magnified by the hashing function. idealmachine is correct in that a longer value is less likely to have a collision than a shorter one.

Your function could also be shorter since md5() will always return a 32 character long string. Try this:

function unique_id($l = 8) {     return substr(md5(uniqid(mt_rand(), true)), 0, $l); } 
like image 111
Jeremy Avatar answered Oct 06 '22 01:10

Jeremy