November 19th, 2008 at 12:29 pm

Lightweight password generator

Here's a snippet of PHP code that can create passwords. It can create passwords of different lengths, it can use different sets (uppercase and lowercase letters as well as numbers), and it can be told to exclude potentially confusing characters.

PHP:
  1. <?php
  2. function passgen($length=8, $reqsets='uln', $noconfusing='true')
  3. {
  4.     $length = (int)$length;
  5.     if ($length> 20 || $length <3) $length = 8;
  6.  
  7.     // some characters look alike. let's optionally exclude them.
  8.     $confusing = ($noconfusing === 'true') ? 'O01Il' : '';
  9.  
  10.     $randchars = $token = '';
  11.  
  12.     $sets = array(
  13.         'u' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
  14.         'l' => 'abcdefghijklmnopqrstuvwxyz',
  15.         'n' => '0123456789'
  16.         // you can even add an own set
  17.     );
  18.  
  19.     if ($reqsets)
  20.     {
  21.         $reqsets = str_split($reqsets);
  22.         foreach ( array_keys($sets) as $availset )
  23.             if ( in_array($availset, $reqsets) )
  24.                 $randchars .= $sets[$availset];
  25.     }
  26.  
  27.     if (!$randchars)
  28.         $randchars = implode($sets);
  29.  
  30.     for ($i=0; $i<=$length; $i++)
  31.     {
  32.         do
  33.         {
  34.             $lpos = mt_rand( 0, strlen($randchars)-1 );
  35.             $letter = substr($randchars, $lpos, 1);
  36.         }
  37.         while ( in_array($letter, str_split($confusing) ) );
  38.  
  39.         $token .= $letter;
  40.     }
  41.     return $token;
  42. }
  43.  
  44. echo passgen($_GET['length'], $_GET['sets'], $_GET['noconfusing']);
  45. ?>

If you intend to use this in a script, please keep in mind that mt_rand() needs to be seeded/initialized properly.

Leave a Comment