Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exactly 30 characters random string creation in php

Tags:

php

random

I am trying to create a random string which should contain 30 characters exactly. But sometimes it is creating 28 characters also. How to solve the issue? My code is like:

function random_string(){
    $character_set_array = array( );
    $character_set_array[ ] = array( 'count' => 15, 'characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ' );
    $character_set_array[ ] = array( 'count' => 6, 'characters' => '0123456789' );
    $character_set_array[ ] = array( 'count' => 9, 'characters' => '!@#$%^&+_|~-=\{}[]:?/' );
    $temp_array = array( );
    foreach ( $character_set_array as $character_set )
    {
      for ( $i = 0; $i < $character_set[ 'count' ]; $i++ )
      {
        $temp_array[ ] = $character_set[ 'characters' ][ rand( 0, strlen( $character_set[ 'characters' ] ) - 1 ) ];
      }
    }
    shuffle( $temp_array );
    return implode( '', $temp_array );
}

please help me.

like image 758
Bappa Avatar asked Jan 01 '26 05:01

Bappa


2 Answers

I executed the function 10.000 times and never got a string with less then 30 characters.

like image 185
Alex Avatar answered Jan 02 '26 19:01

Alex


I could not help rewriting the function. I would not be able to sleep otherwise...

<?php

function random_string(){

        $charset = array();

        $charset[]='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ';
        $charset[]='0123456789';
        $charset[]='!@#$%^&+_|~-=\{}[]:?/';

        $res='';

        for($i=0;$i<30;$i++){
                $j=$charset[array_rand($charset)];
                $res.=$j[mt_rand(0,strlen($j)-1)];
        }

        return($res);
}

// Let us do a long test that the returned random string is always 30 characters long
for($a=0;$a<1000000;$a++){
        $z=random_string();
        if(strlen($z)!=30){print("ERR!!! --> $z");exit;}
}

// If we make it here then all is good... probably.
print("OK!\n");

?>
like image 45
zaf Avatar answered Jan 02 '26 19:01

zaf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!