Log in

View Full Version : Create string with random characters



borris83
03-31-2009, 07:36 AM
Is there any function to create a string with random characters and numbers? This string will be used to create passwords..

codeexploiter
03-31-2009, 09:08 AM
I don't think PHP support a function that can be used to generate a password or a security code. You have to develop it using a custom algorithm. You can also find lots of random password generators in PHP through google.

techietim
03-31-2009, 10:00 AM
function randomAlphanumericPassword($length = 5){
$characters = array_merge(range('a', 'z'), range(0, 9));
shuffle($characters);
$password = array_slice($characters, 0, abs($length));
return implode($password);
}
//EXAMPLE
echo randomAlphanumericPassword(6);

borris83
03-31-2009, 11:06 AM
Hi Techietim!

The function works great.. Thanks

JasonDFR
03-31-2009, 02:23 PM
That is pretty slick Tim. I've never seen one done that way.

Only thing I would do differently is get rid of 0 (Zero), 1 (one) and l (lowercase L).

Nice job.


$characters = array_merge(range('a', 'k'), range('m', 'z'), range(2, 9));

Schmoopy
03-31-2009, 02:47 PM
I can understand the lowercase L being removed, but why take out 1?

JasonDFR
03-31-2009, 03:07 PM
Same reason. Depending on the font, 1 and l can look similar. Get rid of O and I as well if allowing uppercase letters. When something as simple as this can avoid potential problems for some users, why not?

Schmoopy
03-31-2009, 03:10 PM
Fair enough but if it's going to be part of a hyperlink that's randomly generated then there's no point in removing specific letters since the user will click it and not need to worry about there being 1s that look like ls.

But of course, if this is going to be for a different purpose then what you say is true and removing those characters will help to avoid confusion.

JasonDFR
03-31-2009, 03:13 PM
I think it is for generating passwords.
function randomAlphanumericPassword

Schmoopy
03-31-2009, 03:15 PM
I seem to have lost the ability to read today =/

CrazyChop
03-31-2009, 03:49 PM
What about uniqid()? (http://sg.php.net/uniqid)

Something you can try:



$code = md5(uniqid(rand(), true));

techietim
03-31-2009, 07:05 PM
@Crazy

That is a good idea, since it's alphanumeric, but if you ever wanted to expand the function to include other characters it would be more work.