Posted By

javierarce on 09/07/06


Tagged

textmate random unique md5 uniqid


Versions (?)

Who likes this?

20 people have marked this snippet as a favorite

Roshambo
NexusRex
mdavie
blakeb
vali29
Nix
pixelhandler
BD51392
nb109
lfatr
rukoche
suibhne
ewanmacleod
love
loric
colingardom
dhavalpatel
AaronPresley
f1r3fl3x
lfcortes


Generate Random String


 / Published in: PHP
 

Generates a random string of variable length.

  1. function getUniqueCode($length = "")
  2. {
  3. $code = md5(uniqid(rand(), true));
  4. if ($length != "") return substr($code, 0, $length);
  5. else return $code;
  6. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: KyleFarris on October 23, 2008

Very useful. Thanks.

Posted By: EliotRosewater on November 10, 2009

One problem with this function is that the length of the returned string cannot exceed 32 characters, as md5() returns a 32 character string. I have rectified this by making the function recursive, and I have tightened the syntax by using ternary operators:

function getUniqueCode($length = false)
{
    $code = md5(uniqid(rand(), true));

    $code = (strlen($code)
Posted By: EliotRosewater on November 10, 2009

Sorry, it didnt post above:

function getUniqueCode($length = false)
{
    $code = md5(uniqid(rand(), true));
    $code = (strlen($code)

You need to login to post a comment.