Created
April 26, 2010 18:56
-
-
Save abrahamvegh/379736 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Quick-and-dirty password generator, fully-commented edition ;) | |
* | |
* Author: Abraham Vegh <[email protected]> | |
*/ | |
// Our password generator, with a default length of eight | |
function random_password ($length = 8) | |
{ | |
// Create three ranges of characters, merge the resulting arrays into a | |
// single array, and then implode the array to form a 62-character string | |
$select = implode('', array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9))); | |
// Calculate the length of our generated string (62, but we shouldn't have to hard-code this | |
// so we can easily change the available character set later) and subtract one | |
$size = strlen($select) - 1; | |
// Prepare our return variable | |
$return = ''; | |
// The divider between sections in a for() statement is a ; (semicolon) not a , (comma) | |
// We start $i at 0 since arrays in PHP are zero-based | |
// We finish the loop once $i is no longer less than $length, which for the default is 8 characters | |
for ($i = 0; $i < $length; $i++) | |
{ | |
// This is a fun one :) | |
// Here the special { } (curly brace) symbols are used to indicate to PHP that | |
// we want to select a specific character within a string. This is similar to | |
// using [ ] (square brackets) to indicate to PHP which value in an array you | |
// want to select. We then call mt_rand() to generate a random number between zero | |
// and the length of our character selection, minus 1 (remember, zero-based arrays) | |
// Finally, the result of the mt_rand() call is passed directly to the $select{} and | |
// the randomly selected character is added to the return variable, using the convenient | |
// concatenation assignment operator, .= | |
$return .= $select{mt_rand(0, $size)}; | |
} | |
// The loop is completed, and we return (not echo - let the calling code decide what to do with it) | |
return $return; | |
} | |
// Alternatively, here's a heavily compressed and optimized version of the same code :D | |
function rp($a=8){for($b=0,$c='',$d=implode('',array_merge(range('a','z'),range('A','Z'),range(0,9))),$e=strlen($d)-1;$b<$a;$c.=$d{mt_rand(0,$e)},$b++);return $c;} |
It was originally a tutorial for a beginning PHP developer friend of mine; now it's just some fun. ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That has got to be one of the most heavily commented snippets of code I have ever seen!