Wednesday, June 18, 2014

Random String in PHP

I know it's been quite a while and I need to do some SERIOUS reformatting ... For now, here's a quick and easy method to getting a random string in PHP:

 substr(str_shuffle(MD5(microtime())), 0, 10);

That's it! Use it in a function like:

 function str_rand($length=10) { return substr(str_shuffle(MD5(microtime())), 0, $length); }
 echo str_rand();

Max user processing time will be *about .030s on average. Enjoy!


Update! Someone came to me wanting a mix of upper case letters too. Well here you go!

 implode('', array_map(function($i) { return rand(1, 10)%2 == 0 ? strtoupper($i) : $i; }, str_split(substr(str_shuffle(MD5(microtime())), 0, 10))));

That's it! Use it in a function like:

 function str_rand($length=10) { return implode('', array_map(function($i) { return rand(1, 10)%2 == 0 ? strtoupper($i) : $i; }, str_split(substr(str_shuffle(MD5(microtime())), 0, $length)))); }
 echo str_rand();