Update (12/2015): for PHP 7.0 you should use random_int() instead of mt_rand as it provides "cryptographically secure values"
Personally, I like to use sha1(microtime(true).mt_rand(10000,90000)) , but you are looking for a more custom approach, so try this function (which is a modification of your request for this answer ):
function rand_char($length) { $random = ''; for ($i = 0; $i < $length; $i++) { $random .= chr(mt_rand(33, 126)); } return $random; }
However, this is likely to be significantly slower than uniqid (), md5 () or sha1 ().
Edit: It looks like you got to it first, sorry .: D
Edit 2: I decided to do a little test on my Debian machine with PHP 5 and eAccelerator (sorry long code):
function rand_char($length) { $random = ''; for ($i = 0; $i < $length; $i++) { $random .= chr(mt_rand(33, 126)); } return $random; } function rand_sha1($length) { $max = ceil($length / 40); $random = ''; for ($i = 0; $i < $max; $i ++) { $random .= sha1(microtime(true).mt_rand(10000,90000)); } return substr($random, 0, $length); } function rand_md5($length) { $max = ceil($length / 32); $random = ''; for ($i = 0; $i < $max; $i ++) { $random .= md5(microtime(true).mt_rand(10000,90000)); } return substr($random, 0, $length); } $a = microtime(true); for ($x = 0; $x < 1000; $x++) $temp = rand_char(1000); echo "Rand:\t".(microtime(true) - $a)."\n"; $a = microtime(true); for ($x = 0; $x < 1000; $x++) $temp = rand_sha1(1000); echo "SHA-1:\t".(microtime(true) - $a)."\n"; $a = microtime(true); for ($x = 0; $x < 1000; $x++) $temp = rand_md5(1000); echo "MD5:\t".(microtime(true) - $a)."\n";
Results:
Rand: 2.09621596336 SHA-1: 0.611464977264 MD5: 0.618473052979
So my suggestion, if you want speed (but not full encoding), should stick with MD5, SHA-1 or Uniqid (which I haven't tested yet).
St. John Johnson Mar 12 '09 at 4:05 2009-03-12 04:05
source share