PDA

View Full Version : [PHP] Password/Random String Generator


PsychoticDude85
09-23-2006, 02:38 AM
Wrote this for generating passwords and random strings for password reset emails etc, very easy to use. :)

<?php
function strrand($length,$chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
{
// Required Variables
$string = '';
// Loop
for($i = 0; $i <= $length-1; $i++)
$string .= $chars[rand(0,strlen($chars)-1)];
// Return our random string.
return $string;
}
?>
Some examples of implementation:

<?php
echo strrand(40); // Outputs 40 random characters.
echo strrand(20); // Outputs 20 random characters.
echo strrand(30,'abcdefghijklmnopqrstuvwxyz0123456789'); // Outputs 30 characters from just lower-case letters and 0-9
?>

epement
10-10-2006, 04:12 PM
Wrote this for generating passwords and random strings for password reset emails etc, very easy to use. :)

[php]<?php
function strrand($length,
$chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')


When generating random strings for passwords, it's generally best to omit characters which could be confused by users (not you, I mean someone else). For a workplace function, I would probably omit 0 and O, 1 and l (lower-case L) and I (upper-case i), but keep everything else.

Advice from a help-desk staffer.

PsychoticDude85
10-12-2006, 08:40 AM
To be fair, you can make it do so by deleting a few characters or specifying your own characters when the function is called. I see what you mean to a degree, but in most cases the password will be copy/pasted or simply used for a random string confirmation.

For example I use that function to create a confirmation string for my password reset function at pastesite.com, and in that case it just makes it into a link and sends it to the user. In this instance they will either click or copy and paste the link, so readability is not so much an issue as it would be in other scenarios.

For those situation where readability is important - the two methods of making it more so:

- Change the "function" line to function strrand($length,
$chars='abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
or
- Call the function with those chars enforced like this:
strrand(40,'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789');