Portal Home > Knowledgebase > Articles Database > Creating a Random string?


Creating a Random string?




Posted by aldo, 12-28-2007, 06:22 AM
I havent been able to find this but how could I create a like 15-20 character (aA-zZ,0-9) string. I want to use it as a type of session verification for more protection. Anyone know how I can do this?

Posted by Steve_Arm, 12-28-2007, 07:51 AM
function str_random($len) { $val = ''; $charset = "abcdefghijklmnopqrstuvwxyz0123456789"; for ($i = 0; $i < $len; $i++) { $val .= $charset[mt_rand(0, strlen($charset) - 1)]; } return $val; } call it like: $rand_str = str_random(15); // 15 for the length

Posted by aldo, 12-28-2007, 07:53 AM
Ahh Great Thanks!

Posted by Paul-M, 12-28-2007, 02:31 PM
Thats a bit over complicated... I use this:

Posted by phporaclehosting, 01-02-2008, 11:26 AM
The last post did not take into account if length was greater than the character string Here is a fully functional command line app to do what you want. just javac jPasswordGenerator.java and java jPasswordGenerator

Posted by wKkaY, 01-02-2008, 01:35 PM
Not really, considering Steve_Arm's solution returns ideal strings (M^N possibilities versus your M!/(M-N)! ) in just a few extra lines.

Posted by Tim Greer, 01-06-2008, 11:14 PM
Both solutions are fine. My only immediate improvement suggestion would be to just have a character range to pull the letters from (maybe a temp array) of ('A'..'Z", 'a'..'z', 0..9) to save some typing and make it look cleaner. There are thousands of ways to do this. Last edited by Tim Greer; 01-06-2008 at 11:20 PM.

Posted by Dan L, 01-07-2008, 04:02 AM
If you're doing what I think you're doing, you'll want to look into the md5 and sha1 functions.

Posted by Tim Greer, 01-07-2008, 01:30 PM
Did the original poster want this in PHP, too, is another question? There are a great number of ways to do this and some are more or less effective, efficient or secure, but it's a pretty quick and easy thing to do.



Was this answer helpful?

Add to Favourites Add to Favourites    Print this Article Print this Article

Also Read
Hostrocket down ? (Views: 778)

Language: