Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Friday, December 25, 2015

One-line PHP random string generator?

One-line PHP random string generator?


I am looking for the shortest way to generate random/unique strings and for that I was using the following two:

$cClass = sha1(time());  

or

$cClass = md5(time());  

However, I need the string to begin with an an alphabet character, I was looking at base64 encoding but that adds == at the end and then I would need to get rid of that.

What would be the best way to achieve this with one line of code?


Update:

PRNDL came up with a good suggestions wich I ended up using it but a bit modified

echo substr(str_shuffle(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ),0, 1) . substr(str_shuffle(aBcEeFgHiJkLmNoPqRstUvWxYz0123456789),0, 31)  

Would yield 32 characters mimicking the md5 hash but it would always product the first char an alphabet letter, like so;

solution 1

However, Uours really improved upon and his answer;

substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1).substr(md5(time()),1);  

is shorter and sweeter

The other suggestion by Anonymous2011 was very awesome but the first character for some reason would always either M, N, Y, Z so didnt fit my purposes but would have been the chosen answer, btw does anyone know why it would always yield those particular letters?

Here is the preview of my modified version

echo  rtrim(base64_encode(md5(microtime())),"=");  

runner up

Answer by PRNDL Development Studios for One-line PHP random string generator?


If you need it to start with a letter, you could do this. It's messy... but it's one line.

$randomString = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1) . substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);    echo $randomString;  

Answer by RobAtStackOverflow for One-line PHP random string generator?


I have generated this code for you. Simple, short and (resonably) elegant.

This uses the base64 as you mentioned, if length is not important to you - However it removes the "==" using str_replace.

  

Answer by Emilio Gort for One-line PHP random string generator?


I use this function

usage:

 echo randomString(20, TRUE, TRUE, FALSE);      /**     * Generate Random String     * @param Int Length of string(50)     * @param Bool Upper Case(True,False)     * @param Bool Numbers(True,False)     * @param Bool Special Chars(True,False)     * @return String  Random String     */    function randomString($length, $uc, $n, $sc) {        $rstr='';        $source = 'abcdefghijklmnopqrstuvwxyz';        if ($uc)            $source .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';        if ($n)            $source .= '1234567890';        if ($sc)            $source .= '|@#~$%()=^*+[]{}-_';        if ($length > 0) {            $rstr = "";            $length1= $length-1;            $input=array('a','b','c','d','e','f','g','h','i','j,''k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')              $rand = array_rand($input, 1)            $source = str_split($source, 1);            for ($i = 1; $i <= $length1; $i++) {                $num = mt_rand(1, count($source));                $rstr1 .= $source[$num - 1];                $rstr = "{$rand}{$rstr1}";            }        }        return $rstr;    }  

Answer by Uours for One-line PHP random string generator?


Rather than shuffling the alphabet string , it is quicker to get a single random char .

Get a single random char from the string and then append the md5( time( ) ) to it . Before appending md5( time( ) ) remove one char from it so as to keep the resulting string length to 32 chars :

    substr( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,mt_rand( 0 ,50 ) ,1 ) .substr( md5( time() ), 1)  

Lowercase version :

    substr( "abcdefghijklmnopqrstuvwxyz" ,mt_rand( 0 ,25 ) ,1 ) .substr( md5( time( ) ) ,1 )  

Or even shorter and a tiny bit faster lowercase version :

    chr( mt_rand( 97 ,122 ) ) .substr( md5( time( ) ) ,1 )        /* or */        chr( mt_rand( ord( 'a' ) ,ord( 'z' ) ) ) .substr( md5( time( ) ) ,1 )  


A note to anyone trying to generate many random strings within a second:
Since
time( ) returns time in seconds , md5( time( ) ) will be same throughout a given second-of-time due to which if many random strings were generated within a second-of-time, those probably could end up having some duplicates .


I have tested using below code . This tests lower case version :

    $num_of_tests = 100000;        $correct = $incorrect = 0;        for( $i = 0; $i < $num_of_tests; $i++ )      {          $rand_str = substr( "abcdefghijklmnopqrstuvwxyz" ,mt_rand( 0 ,25 ) ,1 ) .substr( md5( time( ) ) ,1 );            $first_char_of_rand_str = substr( $rand_str ,0 ,1 );            if( ord( $first_char_of_rand_str ) < ord( 'a' ) or ord( $first_char_of_rand_str ) > ord( 'z' ) )          {              $incorrect++;              echo $rand_str ,'
'; } else { $correct++; } } echo 'Correct: ' ,$correct ,' . Incorrect: ' ,$incorrect ,' . Total: ' ,( $correct + $incorrect );

Answer by 23kulpamens for One-line PHP random string generator?


I had found something like this:

$length = 10;  $randomString = substr(str_shuffle(md5(time())),0,$length);  echo $randomString;  

Answer by Daniel Reyes for One-line PHP random string generator?


base_convert(microtime(true), 10, 36);

Answer by maaarghk for One-line PHP random string generator?


I decided this question needs a better answer. Like code golf! This also uses a better random byte generator.

preg_replace("/[\/=+]/", "", base64_encode(openssl_random_pseudo_bytes(8)));  

Increase the number of bytes for a longer password, obviously.

Answer by Rudie for One-line PHP random string generator?


Creates a 200 char long hexdec string:

$string = bin2hex(openssl_random_pseudo_bytes(100));  

maaarghk's answer is better though.

Answer by charlesrockbass for One-line PHP random string generator?


I'm using this one to generate dozens of unique strings in a single go, without repeating them, based on other good examples above:

$string = chr(mt_rand(97, 122))            . substr(md5(str_shuffle(time() . rand(0, 999999))), 1);  

This way, I was able to generate 1.000.000 unique strings in ~5 seconds. It's not THAT fast, I know, but as I just need a handful of them, I'm ok with it. By the way, generating 10 strings took less than 0.0001 ms.

Answer by Vipin Kumar R. Jaiswar for One-line PHP random string generator?


JavaScript Solution:

function randomString(pIntLenght) {      var strChars = ?0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz?;    var strRandomstring = ?;      for (var intCounterForLoop=0; intCounterForLoop < pIntLenght; intCounterForLoop++) {        var rnum = Math.floor(Math.random() * strChars.length);        strRandomstring += strChars.substring(rnum,rnum+1);    }     return strRandomstring;  }    alert(randomString(20));  

Reference URL : Generate random string using JavaScript

PHP Solution:

function getRandomString($pIntLength = 30) {        $strAlphaNumericString     = ?0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ?;          $strReturnString         = ?;          for ($intCounter = 0; $intCounter < $pIntLength; $intCounter++) {             $strReturnString .= $strAlphaNumericString[rand(0, strlen($strAlphaNumericString) - 1)];        }        return $strReturnString;  }    echo getRandomString(20);  

Reference URL : Generate random String using PHP

Answer by PavelŠ for One-line PHP random string generator?


This function returns random lowercase string:

function randomstring($len=10){   $randstr='';   for($iii=1; $iii<=$len; $iii++){$randstr.=chr(rand(97,122));};   return($randstr);  };  

Answer by saud khan for One-line PHP random string generator?


You can try this:

 function KeyGenerator($uid) {      $tmp = '';      for($z=0;$z<5;$z++) {        $tmp .= chr(rand(97,122)) . rand(0,100);      }      $tmp .= $uid;      return $tmp;    }  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.