fork(5) download
  1. <?php
  2. /**
  3.  * @link http://stackoverflow.com/questions/9999290/write-a-function-generatepassword-which-accepts-two-arguments-an-integer-and-a
  4.  */
  5.  
  6.  
  7. /**
  8.  * Generate a password N characters long consisting of characters
  9.  *
  10.  * @param int $size
  11.  * @param string $characters
  12.  * @param callback $random (optional) source of random, a function with two parameters, from and to
  13.  * @return string|NULL password
  14.  */
  15. function generate_password($size, $characters, $random = 'rand') {
  16.  
  17. // validate $size input
  18. $size = (int) $size;
  19.  
  20. if ($size <= 0) {
  21. trigger_error(sprintf('Can not create a password of size %d. [%s]', $size, __FUNCTION__), E_USER_WARNING);
  22. return NULL;
  23. }
  24.  
  25. if ($size > 255) {
  26. trigger_error(sprintf('Refused to create a password of size %d as this is larger than 255. [%s]', $size, __FUNCTION__), E_USER_WARNING);
  27. return NULL;
  28. }
  29.  
  30. // normalize $characters input, remove duplicate characters
  31. $characters = count_chars($characters, 3);
  32.  
  33. // validate number of characters
  34. $length = strlen($characters);
  35. if ($length < 1) {
  36. trigger_error(sprintf('Can not create a random password out of %d character(s). [%s]', $length, __FUNCTION__), E_USER_WARNING);
  37. return NULL;
  38. }
  39.  
  40. // initialize the password result
  41. $password = str_repeat("\x00", $size);
  42.  
  43. // get the number of characters minus one
  44. // your string of characters actually begins at 0 and ends on the
  45. // string-length - 1:
  46. // $characters[0] = 'a'
  47. // $characters[1] = 'b'
  48. // $characters[2] = 'c'
  49. $length--;
  50.  
  51. // get one random character per each place in the password
  52. while ($size--)
  53. {
  54. // generate a random number between 0 and $length (including)
  55. $randomValue = $random(0, $length);
  56. // that random number is used to turn the number into a character
  57. $character = $characters[$randomValue];
  58. // set the random character
  59. $password[$size] = $character;
  60. }
  61.  
  62. // return the result
  63. return $password;
  64. }
  65.  
  66.  
  67. echo generate_password(5, 'abc0123');
Success #stdin #stdout 0.02s 13064KB
stdin
Standard input is empty
stdout
ba11c