Archive

Posts Tagged ‘PHP’

Creating a random password with PHP

October 31, 2008 Leave a comment

I have been working on getting my domain back up and running, when I ran into the need for new functionality to automatically create a random password for a user should he or she have forgotten theirs.

The following is a partial solution to what I came up with, along with commentary on what the rest of the functionality entailed.

First confirm that the user is indeed who he or she claims to be.  Good ways of doing this are getting a full name, email address, maybe even a birthday.  Next, for my site I give the ability for a user to create their own secret question and answer to go along with it.  This affords a little more security than having canned secret questions — not much, but a little.  The secret question is presented, and when a correct answer is given, I create an email that sends the random password to their account.

Simple enough, so here is the code for the random password part of this solution:

$chars = 'abcdefghijkmnopqrstuvwxyz023456789!@#$';

srand((double)microtime() * 1000000);

$passwd = '';
for ($i = 0; $i < 10; $i++)
    $passwd .= substr($chars, (rand() % 37), 1);

You will notice that in the $chars string I omitted the characters l and 1. I did this because these two characters could be confused with one another, which is something you do not want when sending a random string to a user.

Simple enough. Enjoy.

Categories: Programming Tags: ,