Posted By

tylerhall on 08/28/07


Tagged

php textmate password


Versions (?)

Who likes this?

31 people have marked this snippet as a favorite

depmed
neuroasis
hudge
pagetoscreen
bioascii
leitmotiv
digitalifer
romanos
pixelhandler
davidhorn
grn
section31
sumandahal
jprice
nb109
vali29
cindreta
dfaulty
kaartz
dantreacy
omerta83
osirisinternet
Darsain
ijasnijas
uilgenstein
adth
claudiowebdesign
tspitzr
lfcortes
SevenLayersDesign
rmethod


Generate a Unambiguous Random Password


 / Published in: PHP
 

This function generates a random password of a specified length in lower or mixed case letters and numbers. Ambiguous characters, such as I, L, 1, 0, and O, are left out so the user can easily read the password.

  1. function random_password($len = 7, $mixed_case = false)
  2. {
  3. $a = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789";
  4. if(!$mixed_case) $a = strtolower($a)
  5. $out = "";
  6. for($i = 0; $i < $len; $i++)
  7. $out .= $a[rand(0, strlen($a))];
  8. return $out;
  9. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: koncept on July 9, 2008

apparently mt_rand() is up to 4x faster

Posted By: jaxx on May 25, 2011

Hmmm... I doubt performance was what was needed anyways.

Precalculating strlen($a) does make a noticable difference, otherwise, a 5 million loop run gives mt_rand() 17.07s and rand() 17.19s on my mac... sure, we're not in 2008 anymore ^^

Posted By: GrooveMule on June 3, 2011

I found an odd error when testing 20 character long mixed case passwords. Most of the time it works, but every once in a while it will only return 19 characters, and give an error saying Notice: Uninitialized string offset: 54 in C:\filepath\index.php on line " $out .= $a[rand(0, strlen($a))];". What would cause the index to go out of the range of the string?

Posted By: GrooveMule on June 3, 2011

The error is due to the rand function call. The function strlen returns the length of the string, but if you use the length in the rand function, which has an inclusive range, then sometimes you will get a reference to an index that is one above the max index, because the index starts at 0.

You need to login to post a comment.