|
|
PHP Snippets
|
Saturday, 2 August 08, 1:22 pm
Rich
|
Random Password GeneratorSeveral times I've come across some rather long-winded solutions to the problem of generating a random string of characters, e.g. for a random password or capcha text for instance.
It's easy to do this using just two lines of PHP, no need for anything complicated:
for ($count = 0; $count < $password_length; $count++) $pword .= chr(rand(65, 90));
The PHP chr() function returns the character with the ASCII value passed in, and the characters with ASCII between 65 and 90 are the capital letters. So this generates a string of random capital letters, eg LXYJNGXOPN. For better passwords, you can include a greater range of ASCII characters. Obviously you only want typable ones, and usually only familiar special characters. The range 33 to 126 includes numbers, lowercase letters and the standard special typable characters. You get passwords such as ^^@1nM+Gx8 and Ov`3[|m3]M. However you often just want numbers and upper/lowercase letters. It's not hard to alter the script to accomplish this:
for ($count = 0; $count < $password_length; $count++) { $ascii_code = rand(55, 115); if ($ascii_code < 65) { $ascii_code -= 7; } elseif ($ascii_code >90) { $ascii_code += 6; } $password .= chr($ascii_code); }
Obviously you just need to set $password_length appropriately beforehand, and hey presto, you get a random password up to that length in the $password variable at the end. These passwords only contain numbers and letters, for example, sAT5Z96hYe and PsOZUZqJT7.
Strip Whitespace from a StringThis is really a PERL Regular Expression tip rather than PHP, but because of PHP's support for RegEx, is readily usable within a PHP script:
echo preg_replace('/\s\s+/', ' ', $string); |
|